熊猫版本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
我想在列替换娜值B
,并C
在列'A”值。
预期输出为
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
我已尝试使用fillnafill
沿着axis 0
,但其不给预期的输出,(其填充从上述列)
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
试图填补所有娜在B
和C
与0
使用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)如何在给定的数据帧中填充列中的na值B
并C
使用列中的值A
?
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句