我试图在我的 DataFrame all_files_d 中用 0 填充所有浮点列 NaN 值,然后将其放入空列表或名为 ts 的 DataFrame 中。
我的数据样本是这样的:
ColX ColY
56.9 6.4
67.5 NaN
NaN 8.9
NaN NaN
我已尝试遵循此问题代码,因为它似乎对某些用户有效,但似乎有 NaN 值并且它没有填充任何内容:
Fillna in multiple columns in place in Python Pandas
这是我的代码:
ts = []
all_files_d.apply(lambda x: x.fillna(0, inplace = True) if x.dtype.kind
in 'f' else x.fillna('.', inplace = True), axis = 1)
ts.append(all_files_d)
我希望得到以下结果,所有 NaN 都用 0 填充。在此先感谢。
ColX ColY
56.9 6.4
67.5 0
0 8.9
0 0
如有任何帮助,我们将不胜感激。
请您参考如下方法:
使用combine_first与 pd.to_numeric() :
测试(添加了一个额外的字符串列):
df['Colz']=['abc',np.nan,'def',np.nan]
print(df)
ColX ColY Colz
0 56.9 6.4 abc
1 67.5 NaN NaN
2 NaN 8,9 def
3 NaN NaN NaN
df.combine_first(df.apply(lambda x: \
pd.to_numeric(x,errors='coerce')).dropna(how='all',axis=1).fillna(0))
输出
ColX ColY Colz
0 56.9 6.4 abc
1 67.5 0 NaN
2 0.0 8,9 def
3 0.0 0 NaN
编辑,用于获取 float 据类型并用 NaN 填充:
m=df.select_dtypes('float').columns
df.loc[:,m]=df.loc[:,m].fillna(0)
print(df)
