【问题标题】:How to sum a single column based on multiple conditions in Python?如何根据 Python 中的多个条件对单列求和?
【发布时间】:2022-01-12 21:47:58
【问题描述】:

最终目标是根据其他列中的多个条件对“价格”列中的值求和。不过我不确定该怎么做。

import pandas as pd

#creating random dataset
rnd = pd.DataFrame({'Status':['Accepted', 'Denied', 'Accepted', 'Accepted', 'Denied'],
                    'Letter':['A 02-02-19', 'AB 10-31-21', 'A 03-07-18', 'CD 11-13-21', 'A 04-05-21'], 
                    'Fruit':['Apple', 'Orange', 'Blueberry', 'Orange', 'Apple'],
                    'Price':[10,20,14,15,29]})

#output of dataframe
rnd
  1. 需要将“已接受”作为“状态”列中的值。我知道这可以通过这样做来完成

    ''' net = rnd.loc(rnd["Status"] == "Accepted", "Price"].sum() '''

但是,我还需要根据“字母”列中出现的内容对其进行汇总。我不关心值中的随机日期,只关心字符串开头的字符。 AB 将被归入与 A 不同的组中,A 也将与 CD 进行不同的分组。如果我只想要那些在信栏中有“A”并且在状态栏中有“接受”的人,我正在试图弄清楚如何对“价格”求和。

【问题讨论】:

  • 请添加您预期的输出数据框

标签: python python-3.x pandas dataframe


【解决方案1】:

试试:

rnd.query('Status == "Accepted"')\
   .groupby(rnd['Letter'].str.split(' ').str[0])['Price'].sum()

输出:

Letter
A     24
CD    15
Name: Price, dtype: int64

【讨论】:

    【解决方案2】:

    一般:

    foo = self.db[(self.db['COL_NAME'] == val1) & (self.db['OTHER_COL'] != 0)]['COL_TO_SUM'].sum()
    

    【讨论】:

      猜你喜欢
      • 2021-05-05
      • 1970-01-01
      • 1970-01-01
      • 2021-01-25
      • 2017-06-20
      • 2020-03-05
      • 2017-04-25
      • 1970-01-01
      相关资源
      最近更新 更多