[英]Python: Pandas cause invalid type of comparison
I have two types of error data that need to corrected. 我有两种类型的错误数据需要更正。 One is with null and one is with Nan. 一个是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
Another type is with NaN 另一种是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
How to replace both null and NaN data with 0? 如何将null和NaN数据都替换为0? My code working if either null or NaN but I can't work for both 我的代码可以为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)
it return error 它返回错误
Traceback (most recent call last): File "", line 1, in File "/home/.local/lib/python2.7/site-packages/pandas/core/ops.py", line 763, in wrapper res = na_op(values, other) File "/home/.local/lib/python2.7/site-packages/pandas/core/ops.py", line 718, in na_op raise TypeError("invalid type comparison")TypeError: invalid type comparison 追溯(最近一次通话最后一次):文件“ /”,第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:无效类型比较
The code will work if volume = df_new['Volume'] == 'null'
but this will not correct the data is it is NaN, and repalce with 0 如果volume = df_new['Volume'] == 'null'
则该代码将起作用,但这将无法纠正数据,因为它是NaN,并用0代替
Use replace
for replace null
and fillna
for replace NaN
s and None
s: 将replace
用于替换null
,将fillna
用于替换NaN
和None
:
df['Volume'] = df['Volume'].replace('null', np.nan).fillna(0)
Or: 要么:
df['Volume'] = df['Volume'].replace('null', 0).fillna(0)
For detect null
or NaN
s add |
要检测null
或NaN
添加|
for bitwise or
and parentheses: 对于按位or
和括号:
volume = (df_new['Volume'] == 'null') | (df_new['Volume'].isnull())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.