【问题标题】:Fill NaN in both columns either values present在两列中填充 NaN 任何值
【发布时间】:2019-05-18 13:33:02
【问题描述】:

我在 df 中有两列,有时在任一列中都有 NaN,有时在两列中都有。如果存在任何列值,我想用相同的值填充 NaN。

例如, 输入:

       col1      col2
0  3.375000  4.075000
1  2.450000  1.567100
2       NaN       NaN
3  3.248083       NaN
4       NaN  2.335725
5  2.150000  3.218750

输出:

       col1      col2
0  3.375000  4.075000
1  2.450000  1.567100
2       NaN       NaN
3  3.248083  3.248083
4  2.335725  2.335725
5  2.150000  3.218750

为此我试过了,

print df.T.fillna(method='bfill').fillna(method='ffill').T

上面给了我一个必需的结果,但我认为我给我的代码增加了更多的复杂性。还有其他更好的方法吗?

【问题讨论】:

标签: python pandas


【解决方案1】:

不用转置,可以指定轴:

df.ffill(1).bfill(1)

       col1      col2
0  3.375000  4.075000
1  2.450000  1.567100
2       NaN       NaN
3  3.248083  3.248083
4  2.335725  2.335725
5  2.150000  3.218750

如果您有多个列,但不想触及其中的一些列,则可以切片、填充和分配回。

df
       col1      col2  col3
0  3.375000  4.075000   NaN
1  2.450000  1.567100   2.0
2       NaN       NaN   3.0
3  3.248083       NaN   5.0
4       NaN  2.335725   NaN
5  2.150000  3.218750   5.0

include = ['col1', 'col2']
# Or,
# exclude = ['col3']
# include = df.columns.difference(exclude)
df[include] = df[include].ffill(1).bfill(1)

df

       col1      col2  col3
0  3.375000  4.075000   NaN
1  2.450000  1.567100   2.0
2       NaN       NaN   3.0
3  3.248083  3.248083   5.0
4  2.335725  2.335725   NaN
5  2.150000  3.218750   5.0

如果只有两列,也可以使用combine_first

df.col1 = df.col1.combine_first(df.col2) 
df.col2 = df.col2.combine_first(df.col1)

       col1      col2
0  3.375000  4.075000
1  2.450000  1.567100
2       NaN       NaN
3  3.248083  3.248083
4  2.335725  2.335725
5  2.150000  3.218750

【讨论】:

  • 感谢您的快速回复,如果我的数据集中有 col3 并且有时还包含 NaN,如何处理它
  • @MohamedThasinah 你想排除 col3 吗?
  • 把它放在一边。我不想为col3 填写任何值。但想保留它是我的数据集。
  • @MohamedThasinah 完成,您只需指定要包含的内容。
猜你喜欢
  • 2021-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-28
  • 2020-09-03
  • 1970-01-01
  • 2021-01-24
  • 1970-01-01
相关资源
最近更新 更多