I am trying to fill none values in a Pandas dataframe with 0's for only some subset of columns.
我试图在Pandas数据帧中填充任何值,只有一些列的子集为0。
When I do:
当我做:
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
The output:
输出:
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
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
.
它用0代替每个None。我想要做的是,只替换a和b列中的Nones,而不是c。
What is the best way of doing this?
这样做的最佳方式是什么?
3 个解决方案
#1
71
You can select your desired columns and do it by assignment:
您可以选择所需的列并按分配执行:
df[['a', 'b']] = df[['a','b']].fillna(value=0)
The resulting output is as expected:
结果输出符合预期:
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
#2
20
You can using dict
, fillna
with different value for different column
您可以使用不同列的不同值的dict,fillna
df.fillna({'a':0,'b':0})
Out[829]:
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
After assign it back
分配后
df=df.fillna({'a':0,'b':0})
df
Out[831]:
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
#3
2
You can avoid making a copy of the object using Wen's solution and inplace=True:
您可以使用Wen的解决方案和inplace = True来避免复制对象:
df.fillna({'a':0, 'b':0}, inplace=True)
print(df)
Which yields:
产量:
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
#1
71
You can select your desired columns and do it by assignment:
您可以选择所需的列并按分配执行:
df[['a', 'b']] = df[['a','b']].fillna(value=0)
The resulting output is as expected:
结果输出符合预期:
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
#2
20
You can using dict
, fillna
with different value for different column
您可以使用不同列的不同值的dict,fillna
df.fillna({'a':0,'b':0})
Out[829]:
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
After assign it back
分配后
df=df.fillna({'a':0,'b':0})
df
Out[831]:
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
#3
2
You can avoid making a copy of the object using Wen's solution and inplace=True:
您可以使用Wen的解决方案和inplace = True来避免复制对象:
df.fillna({'a':0, 'b':0}, inplace=True)
print(df)
Which yields:
产量:
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