Pandas 数据框 fillna() 只有一些列就位 [英] Pandas dataframe fillna() only some columns in place
本文介绍了Pandas 数据框 fillna() 只有一些列就位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在 Pandas 数据框中只为某些列子集填充 0 值.
I am trying to fill none values in a Pandas dataframe with 0's for only some subset of columns.
当我这样做时:
import pandas as pd
df = pd.DataFrame(data={'a':[1,2,3,None],'b':[4,5,None,6],'c':[None,None,7,8]})
print df
df.fillna(value=0, inplace=True)
print df
输出:
a b c
0 1.0 4.0 NaN
1 2.0 5.0 NaN
2 3.0 NaN 7.0
3 NaN 6.0 8.0
a b c
0 1.0 4.0 0.0
1 2.0 5.0 0.0
2 3.0 0.0 7.0
3 0.0 6.0 8.0
它将每个 None
替换为 0
.我想要做的是,只替换 a
和 b
列中的 None
s,而不替换 c
.
It replaces every None
with 0
's. What I want to do is, only replace None
s in columns a
and b
, but not c
.
这样做的最佳方法是什么?
What is the best way of doing this?
推荐答案
您可以选择您想要的列并通过分配来完成:
You can select your desired columns and do it by assignment:
df[['a', 'b']] = df[['a','b']].fillna(value=0)
结果输出符合预期:
a b c
0 1.0 4.0 NaN
1 2.0 5.0 NaN
2 3.0 0.0 7.0
3 0.0 6.0 8.0
这篇关于Pandas 数据框 fillna() 只有一些列就位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文