熊猫版本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


我想用列中的值替换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)



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


尝试使用BC填充0inplace中的所有Na,但这也不能提供预期的输出

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)如何使用给定数据帧中列B中的值填充列CA中的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时,为什么嵌线不起作用。


我认为原因是chained assignments,需要分配回来。


  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

07-24 18:18
查看更多