Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从同一组的其他记录中的值替换数据帧中的NAN值_Python_Pandas_Nan - Fatal编程技术网

Python 从同一组的其他记录中的值替换数据帧中的NAN值

Python 从同一组的其他记录中的值替换数据帧中的NAN值,python,pandas,nan,Python,Pandas,Nan,我有一个数据帧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

我有一个数据帧
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
我想将
A
B
列中的所有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数据帧中执行相同操作?

与正向和反向填充缺失值一起使用:

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

感谢您提供易于复制的问题!