Pandas数据帧:转换symb

2024-10-01 22:37:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用pandas DataFrame。如果打印dataframe,它包含一些用脚本(-)代替数字的列。当我使用数据制作图表时,termninal返回:

TypeError: Empty 'Series': no numeric data to plot

这些脚本(-)数据点不能在制作图形时使用吗?它们需要更换吗?如果是这样,怎么办?在

我写的代码是:

^{pr2}$

示例数据

data.csv

a,b,c,d,e,f,g,h,i,j,k,l,m,n,nn,o,p,q,r,s,t,u,v,w,x,y,z,hh
    12,2798,3.9,3.0,1.1,4.0,0.1,5.0,0.0,-,0.1,35.5,0.2,52.0,1.6,19.0,2.0,36.0,0.1,24.5,0.2,52.0,0.2,2.0,0.0,-,0.2,13.0
    13,2757,8.5,6.0,3.4,15.0,0.1,1.0,0.0,3.0,0.0,-,0.6,6.0,2.5,12.0,2.4,14.0,0.1,41.0,0.3,25.5,0.3,4.0,0.1,5.0,0.1,19.0
    14,2792,18.1,5.0,8.7,24.0,0.1,5.5,0.0,-,0.1,2.0,1.6,3.0,2.6,5.0,3.9,12.0,0.4,4.5,0.9,5.0,0.8,12.0,0.1,24.0,0.2,16.5
    15,2956,29.2,6.0,14.5,25.0,0.5,4.0,0.1,9.5,0.2,1.0,2.1,4.0,2.5,5.5,5.5,10.0,0.8,3.0,2.0,4.5,1.5,6.0,0.3,10.5,0.4,30.0

使用埃文的答案:df.replace(to_replace = '-', value = np.nan, inplace = True)仍然得到相同的错误。在

它适用于第一列,因为这些列没有脚本(-)


Tags: to数据no脚本dataframepandasdata图表
2条回答

好吧,根据你的意见,你有两个选择:

  1. 如果列有-符号,则删除整行。在
  2. 如果列有-符号,则为其设置默认值。在

假设我有以下数据帧:

>>> df = pd.DataFrame({'col1': [1, 2, 3, 4], 'col2': [11, 22, '-', 44], 'col3': ['-', 3, 5, 7]})
>>> df.dtypes
col1     int64
col2    object
col3    object
dtype: object
>>> df
   col1 col2 col3
0     1   11    -
1     2   22    3
2     3    -    5
3     4   44    7

选项1

^{pr2}$

选项2

>>> import numpy as np
>>> for col in df.columns:
...     if df[col].dtype == 'object':
...         df[col] = np.where(df[col] == '-', 0, df[col])  # set `-` symbol values to 0
...         df[col] = df[col].astype(float)  # cast column to float
... 
>>> df
   col1  col2  col3
0     1  11.0   0.0
1     2  22.0   3.0
2     3   0.0   5.0
3     4  44.0   7.0

借用@Scratch'N'Purr的代码,我的解决方案如下:

import numpy as np
import pandas as pd

df = pd.DataFrame({'col1': [1, 2, 3, 4], 'col2': [11, 22, '-', 44], 'col3': ['-', 3, 5, 7]})

数据框:

^{pr2}$

输出:

col1    col2    col3
0   1   11.0    NaN
1   2   22.0    3.0
2   3   NaN     5.0
3   4   44.0    7.0

情节:

import matplotlib.pyplot as plt
df.plot()
plt.show()

{a1}

我没有仔细查看数据;这个解决方案是否符合您的期望?第二,从int到{}在计算上很昂贵,但是对于足够小的数据集来说足够好。在

编辑:参见pandas DataFrame "no numeric data to plot" error

为了绘制NaN,请转换为float。以上(编辑的)代码生成了PNG图像a到hh,基于OP的更新帖子。在

相关问题 更多 >

    热门问题