简体   繁体   English

如何在python中替换熊猫中的整数值?

[英]How to replace integer values in pandas in python?

I have a pandas dataframe as follows. 我有一个熊猫数据框,如下所示。

   a  b  c  d  e
a  0  1  0  1  1
b  1  0  1  6  3
c  0  1  0  1  2
d  5  1  1  0  8
e  1  3  2  8  0

I want to replace values that is below 6 <=5 with 0. So my output should be as follows. 我想将6 <=5以下的值替换为0。所以我的输出应如下所示。

   a  b  c  d  e
a  0  0  0  0  0
b  0  0  0  6  0
c  0  0  0  0  0
d  0  0  0  0  8
e  0  0  0  8  0

I was trying to do this using the following code. 我试图使用以下代码来做到这一点。

df['a'].replace([1, 2, 3, 4, 5], 0)
df['b'].replace([1, 2, 3, 4, 5], 0)
df['c'].replace([1, 2, 3, 4, 5], 0)
df['d'].replace([1, 2, 3, 4, 5], 0)
df['e'].replace([1, 2, 3, 4, 5], 0)

However, I am sure that there is a more easy way of doing this task in pandas. 但是,我确信在熊猫中有一种更简单的方法可以完成此任务。

I am happy to provide more details if needed. 如果需要,我很乐意提供更多详细信息。

Using mask 使用mask

df=df.mask(df<=5,0)
df
Out[380]: 
   a  b  c  d  e
a  0  0  0  0  0
b  0  0  0  6  0
c  0  0  0  0  0
d  0  0  0  0  8
e  0  0  0  8  0

For performance, I recommend np.where . 为了提高性能,我建议使用np.where You can assign the array back inplace using sliced assignment ( df[:] = ... ). 您可以使用切片分配( df[:] = ... )将数组分配回原位。

df[:] = np.where(df < 6, 0, df)
df

   a  b  c  d  e
a  0  0  0  0  0
b  0  0  0  6  0
c  0  0  0  0  0
d  0  0  0  0  8
e  0  0  0  8  0

Another option involves fillna : 另一种选择涉及fillna

df[df>=6].fillna(0, downcast='infer')

   a  b  c  d  e
a  0  0  0  0  0
b  0  0  0  6  0
c  0  0  0  0  0
d  0  0  0  0  8
e  0  0  0  8  0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM