代码之家  ›  专栏  ›  技术社区  ›  Srinivas

熊猫错误类型错误:一元~:“float”的操作数类型错误

  •  0
  • Srinivas  · 技术社区  · 4 年前

    我继承了这段代码

    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值。代码的作用是什么?我的理解是,如果字符串是integer类型,它会尝试将其转换为Int。也请告诉我如何克服这个问题。

    1 回复  |  直到 4 年前
        1
  •  1
  •   Anurag Dabas    4 年前

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

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

    跟着 where() 通过在NaN中填充 fillna() 在你的情况下 ~df.Feature2.str.isnumeric() :

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