【问题标题】:Pandas - handling NaN熊猫 - 处理 NaN
【发布时间】:2020-07-23 22:28:52
【问题描述】:

在这样的数据框中:

df_temp = pd.DataFrame({'Player':['One', 'Two', 'Three'],
                                'Goals':[1, NaN, 1],
                                'Assists':[2, NaN, 1],
                                'ShotBar':[NaN 1, NaN],
                                'ShotDefended':[NaN, 1, NaN],
                                'ShotOut':[3, 2, NaN]})

如何将所有NaN 替换为 1,并将所有其他单元格加 1?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    你可以试试:

    df.iloc[:,1:] = df.iloc[:,1:].fillna(0).add(1)
    

    相当于:

    df.iloc[:,1:] = df.iloc[:,1:].add(1).fillna(1)
    

    输出:

      Player  Goals  Assists  ShotBar  ShotDefended  ShotOut
    0    One    2.0      3.0      1.0           1.0      4.0
    1    Two    1.0      1.0      2.0           2.0      3.0
    2  Three    2.0      2.0      1.0           1.0      1.0
    

    更新:仅适用于数字列:

    num_cols = df.select_dtypes(include=np.number).columns
    df[num_cols] = df[num_cols].fillna(0).add(1)
    

    【讨论】:

    • 我需要用 1 填充 NaN。
    • .add(1) 会将NaN 中的0 转换为1
    • 但我需要将 NaN 转换为 1 并将 1 添加到 1 或以上的所有单元格。你的解决方案就是这样做的吗?
    • 我的代码确实将所有 NaN 替换为 1,并将 1 添加到所有其他单元格,如输出所示。
    • 谢谢。我的例子只是一个虚拟的df。您的解决方案只能为数字类型提供 obs 吗?因为如果我将其应用于真正的 df,我会得到 TypeError: can only concatenate str (not "int") to str,因为某些列中有字符串
    【解决方案2】:

    你为什么不试试这个: 先将NaN全部替换为零,然后加1:

    df = df.fillna(0)
    df[df.columns[1:]]+=1 #skipping the first columns with str
    

    否则你也可以先用 1 添加元素,然后用 1 替换 NaN

    df[df.columns[1:]]+=1
    df = df.fillna(1)
    

    【讨论】:

      【解决方案3】:

      试试这个:

      num_cols = df_temp.select_dtypes('number').columns
      df_temp[num_cols] = df_temp[num_cols].add(1, fill_value=0)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-05
        • 2021-12-15
        • 2014-01-29
        • 2020-01-06
        • 2018-10-20
        • 2019-08-30
        • 1970-01-01
        相关资源
        最近更新 更多