【问题标题】:get max and min values based on conditions in pandas dataframe根据熊猫数据框中的条件获取最大值和最小值
【发布时间】:2021-06-05 13:19:45
【问题描述】:

我有一个这样的数据框

count A B Total
yes 4900 0 0
yes 1000 1000 0
sum_yes 5900 1000 0
yes 4000 0 0
yes 1000 0 0
sum_yes 5000 0 0

我想要这样的结果,即仅针对 'count' = 'sum_yes' 如果 B 的值 =0 的行计算 A 列和 B 列的最大值,否则计算最小值

count A B Total
yes 4900 0 0
yes 1000 1000 0
sum_yes 5900 1000 1000
yes 4000 0 0
yes 1000 0 0
sum_yes 5000 0 5000

到目前为止我已经尝试过了:

df['Total'] = [df[['A', 'B']].where(df['count'] == 'sum_yes').max(axis=0) if 
                   'B'==0 else df[['A', 'B']]
                   .where(df['count'] == 'sum_yes').min(axis=0)]

但是我得到 ValueError Series 的真值是模棱两可的。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()

知道如何解决这个问题

【问题讨论】:

  • 第一个计数行中“sum_yes”的总数应为 1000,即 min(5900, 1000) 但您显示为 0。
  • 是的,你是对的,更正了值

标签: python pandas dataframe min


【解决方案1】:

你可以使用numpy.where:

new_values = np.where((df["count"] == "sum_yes") & (df.B == 0),
                       df.loc[:, ["A", "B"]].max(1),
                       df.loc[:, ["A", "B"]].min(1),
                      )

df.assign(Total = new_values)


     count     A     B  Total
0      yes  4900     0      0
1      yes  1000     0      0
2  sum_yes  5900  1000   1000
3      yes  4000  1000   1000
4      yes  1000     0      0
5  sum_yes  5000     0   5000

【讨论】:

  • Numpy where 类似于 if else 子句... 第一行是条件,如果条件满足则选择第二行,如果失败则选择第三行。第二行和第三行只需选择 A 和 B 的最大值或最小值
  • 感谢您的解释
猜你喜欢
  • 2017-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-04
  • 1970-01-01
  • 2019-01-17
  • 2018-10-18
  • 2020-04-28
相关资源
最近更新 更多