繁体   English   中英

用熊猫数据框中另一列的值在多列中填充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

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

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)

输出: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

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

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列中的na值?
2)当在数据帧的子集上使用fillna时,为什么嵌线不起作用。
3)如何沿行ffill (已实现)?

1)如何使用给定数据帧中A列的值填充BandC列中的na值?

因为未实现按列替换,所以可能的解决方案是双重转置:

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)当在数据帧的子集上使用fillna时,为什么嵌线不起作用。

我认为原因是链接分配 ,需要分配回来。

3)如何沿行填充(已实现)?

如果分配回来,则用向前填充工作不错的方法代替:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM