【问题标题】:Pandas error TypeError: bad operand type for unary ~: 'float'Pandas错误TypeError:一元操作数类型错误〜:'float'
【发布时间】:2021-07-31 16:02:32
【问题描述】:

我继承了这段代码

dummy_data1 = {
    'id': ['1', '2', '3', '4', '5'],
    'Feature1': ['A', 'C', 'E', 'G', 'I'],
    'Feature2': ['Mouse', 'dog', 'house and parrot', '23', np.NaN],
    'dates': ['12/12/2020','12/12/2020','12/12/2020','12/12/2020','12/12/2020']}

df1 = pd.DataFrame(dummy_data1, columns = ['id', 'Feature1', 'Feature2', 'dates'])

df1 = df1.assign(
                    Feature2=lambda df: df.Feature2.where(
                        ~df.Feature2.str.isnumeric(),
                        pd.to_numeric(df.Feature2, errors="coerce").astype("Int64"),
                    )
    )
    
print(df1)

我知道这是因为 np.NAN 值。代码有什么作用?我的理解是,如果它是整数类型,它会尝试将字符串转换为 Int。另外请告诉我如何克服这个问题。

【问题讨论】:

  • 根据您的需要用 fillna() 填充那些 NaN 为 True 或 False

标签: python-3.x pandas


【解决方案1】:

您可以通过pd.to_numeric() 尝试然后填写NaN:

df['Feature2']=pd.to_numeric(df['Feature2'], errors="coerce").fillna(df['Feature2'])

通过在您的条件~df.Feature2.str.isnumeric() 中用fillna() 填充那些NaN 来满足where() 条件:

df['Feature2']=df['Feature2'].where(~df.Feature2.str.isnumeric().fillna(True),
                     pd.to_numeric(df.Feature2, errors="coerce").astype("Int64")
                    )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-17
    • 1970-01-01
    • 2013-08-11
    • 2013-03-28
    • 2023-03-31
    • 1970-01-01
    • 2019-07-11
    • 2018-08-08
    相关资源
    最近更新 更多