【问题标题】:Pandas: How to do groupby with conditions in pandas dataframe?熊猫:如何根据熊猫数据框中的条件进行分组?
【发布时间】:2022-01-25 21:38:41
【问题描述】:

我应该做 groupby(country and product) 和 Value column 应该包含 count(id) where status is closed,我需要返回所有剩余的列。

Sample input

id        status    ticket_time           product      country    name
126       open      2021-10-04 01:20:00   Broad        A          metric
299       open      2021-10-02 00:00:00   Fixed        B          metric
376       closed    2021-10-01 00:00:00   Fixed        C          metric
370       closed    2021-10-04 00:00:00   Broad        C          metric
372       closed    2021-10-04 00:00:00   TV           D          metric
605       closed    2021-10-01 00:00:00   TV           D          metric

输出格式示例

country  product   name      ticket_time            Value(count(id)where status closed)
D        TV        metric    YYYY-MM-DD HH:MM:SS          2
C        Broad     metric    YYYY-MM-DD HH:MM:SS          1
C        Fixed     metric    YYYY-MM-DD HH:MM:SS          1
....      ...      ....                  ...               ...       

我尝试了以下代码:


df1 = df[df['status'] == 'closed']
df1['Value'] = df1.groupby(['country', 'product'])['status'].transform('size')

df = df1.drop_duplicates(['country', 'product']).drop('status',axis=1).drop(['id'], axis = 1)

有没有更好的方法来解决这个问题?

【问题讨论】:

  • 请提供您的数据框作为代码

标签: python python-3.x pandas dataframe pandas-groupby


【解决方案1】:

不要使用groupby+transform,而是使用groupby+agg:

(df.loc[df['status'].eq('closed')]
   .groupby(['country', 'product'], as_index=False)
   .agg({'name': 'first', 'ticket_time': 'first', 'status': 'size'})
   .rename(columns={'status': 'Value count(size)'})
)

输出:

  country product    name          ticket_time  Value count(size)
0       C   Broad  metric  2021-10-04 00:00:00                  1
1       C   Fixed  metric  2021-10-01 00:00:00                  1
2       D      TV  metric  2021-10-04 00:00:00                  2

【讨论】:

  • 非常感谢@mozway。它适用于我的实际数据集。但是我的输入数据集(例如 set_name、run_time)列还有一些列,我想将这两列也添加到我的输出中。你能帮忙吗
  • 我在 agg func 中添加了额外的两列,它可以工作。非常感谢@mozway
  • @Anos 很高兴它成功了!
猜你喜欢
  • 2021-11-13
  • 2021-08-27
  • 2019-02-15
  • 2022-11-14
  • 1970-01-01
  • 2021-11-02
  • 2019-05-15
  • 2021-12-28
  • 1970-01-01
相关资源
最近更新 更多