首页 > 解决方案 > 用列中的值填充数据框中的所有 nan 值

问题描述

我有一个这样的df

index      a      b      c
0          0      0      1
1          nan    1      2
2          0      1      3
3          1      nan    4 
4          1      0      5
5          nan    0      6
6          nan    nan    7

我想用最后一列的值填充前两列(实际上是前 20 列),即

index      a      b      c
0          0      0      1
1          2      1      2
2          0      1      3
3          1      4      4 
4          1      0      5
5          6      0      6
6          7      7      7

我正在考虑使用 df.iloc[:,0:1].fillna(df['c']) 之类的东西,但是它仅在我选择一列时才有效,如果选择了多个列,则所有内容都将保持为 nan。我想使用 iloc (或使用索引而不是列名)使用最后一列的值来填充前 20ish 列。

标签: pythonpandasdataframe

解决方案


做就是了

out = df.fillna(dict.fromkeys(list(df),df.c))
Out[206]: 
     a    b  c
0  0.0  0.0  1
1  2.0  1.0  2
2  0.0  1.0  3
3  1.0  4.0  4
4  1.0  0.0  5
5  6.0  0.0  6
6  7.0  7.0  7

推荐阅读