【问题标题】:Group by with multiple conditions in pandas [duplicate]在熊猫中按多个条件分组[重复]
【发布时间】:2018-12-24 14:47:12
【问题描述】:

我想聚合行,对两列使用不同的条件。

当我执行 df.groupby('[a]').agg('count') 时,我得到 输出 1

当我执行 df.groupby('[a]').agg('mean') 时,我得到 输出 2

有没有办法进行聚合,将输出 1 显示到 column[b] 并将输出 2 显示到 column[c]

【问题讨论】:

  • df.groupby('a').agg({'b':'count','c':'mean'})

标签: python pandas group-by aggregate


【解决方案1】:

下面的代码应该可以工作:

# Import libraries
import pandas as pd
import numpy as np

# Create sample dataframe
df = pd.DataFrame({'a': ['A1', 'A1', 'A2', 'A3', 'A4', 'A3'],
                   'value': [1,2,3,4,5,6]})

# Calculate count, mean 
temp1 = df.groupby(['a']).count().reset_index().rename(columns={'value':'count'})
temp2 = df.groupby(['a'])['value'].mean().reset_index().rename(columns={'value':'mean'})

# Add columns to existing dataframe
df.merge(temp1, on='a', how='inner').merge(temp2, on='a', how='inner')

# Add columns to a new dataframe
df2 = temp1.merge(temp2, on='a', how='inner')
df2

【讨论】:

    猜你喜欢
    • 2017-12-14
    • 2017-10-03
    • 2020-01-25
    • 2022-11-28
    • 2022-07-19
    • 1970-01-01
    • 1970-01-01
    • 2019-12-15
    • 2021-12-13
    相关资源
    最近更新 更多