在 pandas 列上执行条件操作 [英] Perform a conditional operation on a pandas column
本文介绍了在 pandas 列上执行条件操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道这应该很简单,但是我想从熊猫中摘取专栏 数据框,并且仅对于满足某些条件(例如小于1)的条目, 乘以标量(例如2).
I know that this should be simple, but I want to take a column from a pandas dataframe, and for only the entries which meet some condition (say less than 1), multiply by a scalar (say 2).
例如,在此数据框中,
df = pd.DataFrame(randn(5,4),index='A B C D E'.split(),columns='W X Y Z'.split())
W X Y Z
A 2.706850 0.628133 0.907969 0.503826
B 0.651118 -0.319318 -0.848077 0.605965
C -2.018168 0.740122 0.528813 -0.589001
D 0.188695 -0.758872 -0.933237 0.955057
E 0.190794 1.978757 2.605967 0.683509
如果我有兴趣在列W
上执行此操作,则结果应为
if I'm interested in carrying out this operation on column W
, the result should be
W X Y Z
A 2.706850 0.628133 0.907969 0.503826
B 1.302236 -0.319318 -0.848077 0.605965
C -4.036336 0.740122 0.528813 -0.589001
D 0.37739 -0.758872 -0.933237 0.955057
E 0.381588 1.978757 2.605967 0.683509
我有以下内容用于绝对作业:
I have the below for an absolute assignment:
df.loc[df['W'] < 1, 'W'] = 4
但是我不确定如何使用W
中的实际值.
but I'm not sure how to use the actual values from W
.
提前谢谢!
推荐答案
在您的情况下,只需使用*=
运算符就可以进行乘法运算:
In your case, just use the *=
operator to make your multiplication in place:
如果您的原始数据框如下所示:
If your Original dataframe looks like:
>>> df
W X Y Z
0 2.706850 0.628133 0.907969 0.503826
1 0.651118 -0.319318 -0.848077 0.605965
2 -2.018168 0.740122 0.528813 -0.589001
3 0.188695 -0.758872 -0.933237 0.955057
4 0.190794 1.978757 2.605967 0.683509
您可以使用:
df.loc[df['W'] < 1, 'W'] *= 2
导致的结果:
>>> df
W X Y Z
0 2.706850 0.628133 0.907969 0.503826
1 1.302236 -0.319318 -0.848077 0.605965
2 -4.036336 0.740122 0.528813 -0.589001
3 0.377390 -0.758872 -0.933237 0.955057
4 0.381588 1.978757 2.605967 0.683509
这等效于以下内容:
df.loc[df['W'] < 1, 'W'] = df.loc[df['W'] < 1, 'W'] * 2
这篇关于在 pandas 列上执行条件操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文