pandas 数据框fillna()仅存在一些列 [英] Pandas dataframe fillna() only some columns in place
本文介绍了 pandas 数据框fillna()仅存在一些列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只尝试对列的某些子集用0填充Pandas数据框中的任何值.
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
,而不能替换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屋!
查看全文