用 pandas 数据框中另一列的值填充多列中的 Na

Fill Na in multiple columns with values from another column within the pandas data frame

Pandas 版本 0.23.4, python 版本 3.7.1
我有一个数据框 df 如下

df = pd.DataFrame([[0.1, 2, 55, 0,np.nan],
                   [0.2, 4, np.nan, 1,99],
                   [0.3, np.nan, 22, 5,88],
                   [0.4, np.nan, np.nan, 4,77]],
                   columns=list('ABCDE'))
     A    B     C  D     E
0  0.1  2.0  55.0  0   NaN
1  0.2  4.0   NaN  1  99.0
2  0.3  NaN  22.0  5  88.0
3  0.4  NaN   NaN  4  77.0

我想用“A”列中的值替换 BC 列中的 Na 值。

预期输出为

     A   B      C    D      E 
0   0.1  2.0    55.0   0    NaN 
1   0.2  4.0    0.2    1    99.0 
2   0.3  0.3    22.0   5    88.0 
3   0.4  0.4    0.4    4    77.0

我已经尝试使用 fillaxis 0 的 fillna,但它没有给出预期的输出,(它从上面的列中填充)

df.fillna(method='ffill',axis=0, inplace = True)
    A    B     C   D     E
0  0.1  2.0  55.0  0   NaN
1  0.2  4.0  55.0  1  99.0
2  0.3  4.0  22.0  5  88.0
3  0.4  4.0  22.0  4  77.0  

df.fillna(method='ffill',axis=1, inplace = True)

output: NotImplementedError:

也尝试过

df[['B','C']] = df[['B','C']].fillna(df.A)
output:
    A    B     C   D     E
0  0.1  2.0  55.0  0   NaN
1  0.2  4.0   NaN  1  99.0
2  0.3  NaN  22.0  5  88.0
3  0.4  NaN   NaN  4  77.0

试图用 0 填充 BC 中的所有 Na,使用 inplace,但这也没有给出预期的输出

df[['B','C']].fillna(0,inplace=True)
output:
     A    B     C  D     E
0  0.1  2.0  55.0  0   NaN
1  0.2  4.0   NaN  1  99.0
2  0.3  NaN  22.0  5  88.0
3  0.4  NaN   NaN  4  77.0

填充0到数据帧的切片如果分配回相同的子集将起作用

df[['B','C']] = df[['B','C']].fillna(0)
output:
     A    B     C  D     E
0  0.1  2.0  55.0  0   NaN
1  0.2  4.0   0.0  1  99.0
2  0.3  0.0  22.0  5  88.0
3  0.4  0.0   0.0  4  77.0

1) 如何使用给定数据框的 A 列中的值填充 BC 列中的值?
2) 还有为什么在数据框的子集上使用 fillna 时 inlace 不起作用。
3)如何ffill沿行(实现了吗)?

1) How to fill na values in columns BandC using values from column A from the given data frame ?

由于未实现按列替换,可能的解决方案是双转置:

df[['B','C']] = df[['B','C']].T.fillna(df['A']).T
print (df)
     A    B     C  D     E
0  0.1  2.0  55.0  0   NaN
1  0.2  4.0   0.2  1  99.0
2  0.3  0.3  22.0  5  88.0
3  0.4  0.4   0.4  4  77.0

或者:

m = df[['B','C']].isna()
df[['B','C']] = df[['B','C']].mask(m, m.astype(int).mul(df['A'], axis=0))
print (df)
     A    B     C  D     E
0  0.1  2.0  55.0  0   NaN
1  0.2  4.0   0.2  1  99.0
2  0.3  0.3  22.0  5  88.0
3  0.4  0.4   0.4  4  77.0

2) Also why is inlace not working when using fillna on a subset of the data frame.

我认为原因是 chained assignments,需要重新分配。

3) How to do ffill along the rows(is it implemented)?

用正向填充替换工作很好,如果分配回来:

df1 = df.fillna(method='ffill',axis=1)
print (df1)
     A    B     C    D     E
0  0.1  2.0  55.0  0.0   0.0
1  0.2  4.0   4.0  1.0  99.0
2  0.3  0.3  22.0  5.0  88.0
3  0.4  0.4   0.4  4.0  77.0

df2 = df.fillna(method='ffill',axis=0)
print (df2)
     A    B     C  D     E
0  0.1  2.0  55.0  0   NaN
1  0.2  4.0  55.0  1  99.0
2  0.3  4.0  22.0  5  88.0
3  0.4  4.0  22.0  4  77.0