只有在满足另一列的条件时,Pandas才对该列应用函数

llmtgqce  于 2022-12-16  发布在  其他
关注(0)|答案(3)|浏览(170)

我有一个 Dataframe :

  1. df = A. Cond Val
  2. 1. True 0.8
  3. 5. False 0.8
  4. 2. False 0.6
  5. 4. False 0.5

我想更新列'Val'的值,只在Cond为False且val大于0.55时将其截断为0.1。因此,新df将为:

  1. df = A. Cond Val
  2. 1. True 0.8
  3. 5. False 0.7
  4. 2. False 0.5
  5. 2. False 0.5

做这件事最好的方法是什么?

pvcm50d1

pvcm50d11#

boolean indexingDataFrame.loc配合使用,对于测试False值,将maks反转为~,并通过Series.gt链接另一个掩码:

  1. df.loc[df['Val'].gt(0.55) & ~df['Cond'], 'Val'] -= 0.1
  2. print (df)
  3. A. Cond Val
  4. 0 1.0 True 0.8
  5. 1 5.0 False 0.7
  6. 2 2.0 False 0.5
  7. 3 4.0 False 0.5
qnyhuwrf

qnyhuwrf2#

使用具有两个条件和AND(&)的布尔索引:

  1. df.loc[df['Val'].gt(0.55) & ~df['Cond'], 'Val'] -= 0.1

输出:

  1. A. Cond Val
  2. 0 1.0 True 0.8
  3. 1 5.0 False 0.7
  4. 2 2.0 False 0.5
  5. 3 4.0 False 0.5

条件:

  1. A. Cond Val df['Val'].gt(0.55) ~df['Cond'] AND
  2. 0 1.0 True 0.8 True False False
  3. 1 5.0 False 0.8 True True True
  4. 2 2.0 False 0.6 True True True
  5. 3 4.0 False 0.5 False True False
展开查看全部
nbewdwxp

nbewdwxp3#

使用布尔值的int值,这也可以工作:

  1. df['val'] -= 0.1*(~df['cond'])*(df['val'] > 0.55)

相关问题