我有一个 Dataframe :
df = A. Cond Val 1. True 0.8 5. False 0.8 2. False 0.6 4. False 0.5
df = A. Cond Val
1. True 0.8
5. False 0.8
2. False 0.6
4. False 0.5
我想更新列'Val'的值,只在Cond为False且val大于0.55时将其截断为0.1。因此,新df将为:
df = A. Cond Val 1. True 0.8 5. False 0.7 2. False 0.5 2. False 0.5
5. False 0.7
2. False 0.5
做这件事最好的方法是什么?
pvcm50d11#
将boolean indexing与DataFrame.loc配合使用,对于测试False值,将maks反转为~,并通过Series.gt链接另一个掩码:
boolean indexing
DataFrame.loc
False
~
Series.gt
df.loc[df['Val'].gt(0.55) & ~df['Cond'], 'Val'] -= 0.1print (df) A. Cond Val0 1.0 True 0.81 5.0 False 0.72 2.0 False 0.53 4.0 False 0.5
df.loc[df['Val'].gt(0.55) & ~df['Cond'], 'Val'] -= 0.1
print (df)
A. Cond Val
0 1.0 True 0.8
1 5.0 False 0.7
2 2.0 False 0.5
3 4.0 False 0.5
qnyhuwrf2#
使用具有两个条件和AND(&)的布尔索引:
&
输出:
A. Cond Val0 1.0 True 0.81 5.0 False 0.72 2.0 False 0.53 4.0 False 0.5
条件:
A. Cond Val df['Val'].gt(0.55) ~df['Cond'] AND0 1.0 True 0.8 True False False1 5.0 False 0.8 True True True2 2.0 False 0.6 True True True3 4.0 False 0.5 False True False
A. Cond Val df['Val'].gt(0.55) ~df['Cond'] AND
0 1.0 True 0.8 True False False
1 5.0 False 0.8 True True True
2 2.0 False 0.6 True True True
3 4.0 False 0.5 False True False
nbewdwxp3#
使用布尔值的int值,这也可以工作:
df['val'] -= 0.1*(~df['cond'])*(df['val'] > 0.55)
3条答案
按热度按时间pvcm50d11#
将
boolean indexing
与DataFrame.loc
配合使用,对于测试False
值,将maks反转为~
,并通过Series.gt
链接另一个掩码:qnyhuwrf2#
使用具有两个条件和AND(
&
)的布尔索引:输出:
条件:
nbewdwxp3#
使用布尔值的int值,这也可以工作: