【问题标题】:How to replace an empty value of a particular column with a certain value in Pandas?如何用 Pandas 中的某个值替换特定列的空值?
【发布时间】:2020-12-28 05:07:12
【问题描述】:

例如,我有一个这样的 CSV 文件

id name item Qty
1 Sta bread 67
2 Danny butter
3 Elle cheese
4 Mark coffee 9

我想用 0 替换空的数量值。我试过了:

import pandas as pd

df = pd.read_csv("sample.csv")
df.loc[df['Qty'] =='','Qty']=0

但这不是替换空值。任何解决此问题的建议。

【问题讨论】:

    标签: python python-3.x pandas dataframe numpy


    【解决方案1】:

    你也可以使用fillna

    df['Qty']=df['Qty'].fillna('0').astype(int)
    

    输入Sample.csv

    id,name,item,Qty
    1,Sta,bread,67
    2,Danny,butter,
    3,Elle,cheese,
    4,Mark,coffee,9
    

    输出

    import pandas as pd
    df = pd.read_csv("sample.csv")
    print(df)
       id   name    item   Qty
    0   1    Sta   bread  67.0
    1   2  Danny  butter   NaN
    2   3   Elle  cheese   NaN
    3   4   Mark  coffee   9.0
    df['Qty']=df['Qty'].fillna('0').astype(int)
    print(df)
       id   name    item Qty
    0   1    Sta   bread  67
    1   2  Danny  butter   0
    2   3   Elle  cheese   0
    3   4   Mark  coffee   9
    

    【讨论】:

    • 它们不是NaNs,它们是空字符串
    • 这会将所有数量替换为 0
    • 啊!但是没有价值。缺失值不意味着NaN吗? @U11-转发
    • @ArunPalanisamy 不,他们的意思是''
    • 但我将 OP 示例数据复制粘贴到 csv 中。当我打印时,它会为那些缺失的值提供NaN。@U11-Forward
    【解决方案2】:

    尝试只使用replace

    df['Qty'] = df['Qty'].replace('', 0).astype(int)
    

    所以完整的代码是:

    import pandas as pd
    
    df = pd.read_csv("sample.csv")
    df['Qty'] = df['Qty'].replace('', 0).astype(int)
    print(df)
    

    【讨论】:

    • 您的代码在 qty 字段中替换为 67.0 ,9.0 但不是空值
    • @AtomStore 什么意思?
    • 它用 67.0 代替 67,用 9.0 代替 9,而不是用 0 代替空值
    • @AtomStore 我编辑了我的答案,如果可行,请点赞并接受
    • 由于存在空值,因此引发 ValueError: Cannot convert non-finite values (NA or inf) to integer
    猜你喜欢
    • 2022-11-20
    • 2018-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-18
    • 1970-01-01
    • 2018-10-13
    相关资源
    最近更新 更多