【问题标题】:Python: Pandas cause invalid type of comparisonPython:熊猫导致无效的比较类型
【发布时间】:2018-03-07 12:48:35
【问题描述】:

我有两种类型的错误数据需要更正。一个是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)

返回错误

Traceback(最近一次调用最后一次):文件“”,第 1 行,in 文件 “/home/.local/lib/python2.7/site-packages/pandas/core/ops.py”,行 763,在包装器 res = na_op(values, other) 文件中 “/home/.local/lib/python2.7/site-packages/pandas/core/ops.py”,行 718、在 na_op 中引发 TypeError("invalid type comparison")TypeError: 无效的类型比较

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

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    使用replace 替换nullfillna 替换NaNs 和Nones:

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

    或者:

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

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

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

    【讨论】:

    • 对不起,需要先检测pandas数据帧是否包含NaN或null,对吗?问题出在volume = df_new['Volume'] == 'null' or df_new['Volume'].isnull()
    • 那么需要volume = (df_new['Volume'] == 'null') | (df_new['Volume'].isnull())
    • volume = (df_new['Volume'] == 'null') | (df_new['Volume'].isnull()) 仍然返回错误TypeError: invalid type comparison
    • 那就试试volume = (df_new['Volume'].values == 'null') | (df_new['Volume'].isnull())
    • volume = (df_new['Volume'].astype(str) == 'null') | (df_new['Volume'].isnull()),因为似乎有混合值 - 数字和字符串
    猜你喜欢
    • 2017-02-21
    • 2014-03-31
    • 2017-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-20
    • 1970-01-01
    相关资源
    最近更新 更多