熊猫-处理NaN

时间:2020-07-23 13:45:24

标签: python pandas

在这样的数据框中:

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?

3 个答案:

答案 0 :(得分:2)

您可以尝试:

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 :(得分:0)

您为什么不尝试以下操作: 首先将所有NaN替换为零,然后添加1:

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

否则,您也可以先将元素添加为1,然后将NaN替换为1:

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

答案 2 :(得分:0)

尝试一下:

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