繁体   English   中英

Python:熊猫导致无效的比较类型

[英]Python: Pandas cause invalid type of comparison

我有两种类型的错误数据需要更正。 一个是null,另一个是Nan。

 >>> df_new
          Volume Price   
Date
2017-01-01 500  760
2017-01-02 null 760
2017-01-03 50   770
2017-01-04 null 780

另一种是NaN

 >>> df_new
          Volume Price   
Date
2017-01-01 500  760
2017-01-02 NaN 760
2017-01-03 50  770
2017-01-04 NaN 780

如何将null和NaN数据都替换为0? 我的代码可以为null或NaN,但是我不能同时为两者工作

volume = df_new['Volume'] == 'null' or df_new['Volume'].isnull()
df_new.loc[volume,'Volume'] = 0
df_new.replace('null',np.NaN,inplace=True)
df_new.iloc[0].fillna(df_new.iloc[1].Open,inplace=True)

它返回错误

追溯(最近一次通话最后一次):文件“ /”,第1行,在文件“ /home/.local/lib/python2.7/site-packages/pandas/core/ops.py”中,行763,在包装器res = na_op(值,其他)文件“ /home/.local/lib/python2.7/site-packages/pandas/core/ops.py”,行718,在na_op中引发TypeError(“无效类型比较”)TypeError:无效类型比较

如果volume = df_new['Volume'] == 'null'则该代码将起作用,但这将无法纠正数据,因为它是NaN,并用0代替

replace用于替换null ,将fillna用于替换NaNNone

df['Volume'] = df['Volume'].replace('null', np.nan).fillna(0)

要么:

df['Volume'] = df['Volume'].replace('null', 0).fillna(0)

要检测nullNaN添加| 对于按位or和括号:

volume = (df_new['Volume'] == 'null') | (df_new['Volume'].isnull())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM