【问题标题】:Replacing NAN value in a pandas dataframe from values in other records of same group从同一组的其他记录中的值替换熊猫数据框中的 NAN 值
【发布时间】:2019-05-10 20:16:39
【问题描述】:

我有一个数据框df

import pandas as pd
import numpy as np

df = pd.DataFrame({'A': [np.nan, 1, 2,np.nan,2,np.nan,np.nan], 
               'B': [10, np.nan, np.nan,5,np.nan,np.nan,7], 
               'C': [1,1,2,2,3,3,3]})

看起来像:

     A     B  C
0  NaN  10.0  1
1  1.0   NaN  1
2  2.0   NaN  2
3  NaN   5.0  2
4  2.0   NaN  3
5  NaN   NaN  3
6  NaN   7.0  3

我想将AB 列中的所有NAN 值替换为来自C 列中提到的同一组的其他记录的值。

我的预期输出是:

     A     B   C
0  1.0   10.0  1
1  1.0   10.0  1
2  2.0    5.0  2
3  2.0    5.0  2
4  2.0    7.0  3
5  2.0    7.0  3
6  2.0    7.0  3

如何在 pandas 数据框中做同样的事情?

【问题讨论】:

  • 感谢您提供易于重现的问题!

标签: python pandas nan


【解决方案1】:

使用GroupBy.apply 前后填充缺失值:

df[['A','B']] = df.groupby('C')['A','B'].apply(lambda x: x.ffill().bfill())
print (df)

     A     B  C
0  1.0  10.0  1
1  1.0  10.0  1
2  2.0   5.0  2
3  2.0   5.0  2
4  2.0   7.0  3
5  2.0   7.0  3
6  2.0   7.0  3

【讨论】:

    猜你喜欢
    • 2021-09-08
    • 2017-01-14
    • 2019-02-02
    • 2023-03-03
    • 2020-07-31
    • 2018-04-26
    • 2018-09-29
    • 1970-01-01
    相关资源
    最近更新 更多