【问题标题】:How to apply a function to a dataframe row based on a condition and values of another row?如何根据另一行的条件和值将函数应用于数据框行?
【发布时间】:2021-04-20 01:28:44
【问题描述】:

如果我有一个 pandas 数据框,例如:

a   b   c  
1   2   3 
1   2  -3
2   3   2
4   2  -1

如何根据c中的值是正还是负来改变b列的值,并在操作中使用b和a中的值。

我想在每一行上运行这样的东西:

   if (c >= 0):
     b = a - b
   else:
     b = b - a 

并获取数据框:

a   b   c  
1  -1   3 
1   1  -3
2  -1   2
4  -2  -1

【问题讨论】:

  • for 循环可能吗?
  • 使用np.where : df.assign(b=np.where(df.c.ge(0), df.a - df.b, df.b - df.a))

标签: python pandas dataframe if-statement iteration


【解决方案1】:

您可以使用numpy.where,它类似于if/else,通常更快:

  df.assign(b=np.where(df.c.ge(0), df.a - df.b, df.b - df.a))

    a    b   c
0   1   -1   3
1   1    1  -3
2   2   -1   2
3   4   -2  -1

或者,您可以使用 pandas 的 where 方法,它提供了类似的方法:

 df.assign(b=df.a.sub(df.b).where(df.c.ge(0), df.b - df.a))

    a    b   c
0   1   -1   3
1   1    1  -3
2   2   -1   2
3   4   -2  -1

【讨论】:

  • 完美!谢谢
【解决方案2】:

pandas.DataFrame.apply 可以得到同样的结果:

df['b'] = df.apply(lambda x: x.a - x.b if x.c >= 0 else x.b - x.a, axis = 1)
#   a  b  c
#0  1 -1  3
#1  1  1 -3
#2  2 -1  2
#3  4 -2 -1

【讨论】:

  • 通常比在 numpy/pandas 中使用内置函数要慢
  • @sammywemmy 我同意。能做比较就好了,我现在做不到
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-02-10
  • 1970-01-01
  • 2023-01-07
  • 2021-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多