例子df

retailer_dict = {
    'id': [1, 2, 3, 1, 1, 3],
    'gender': ['Men', 'Women', 'Men', 'Women', 'Men', 'Women'],
    'category': ['western', 'formal', 'casual', 'western', 'formal', 'casual']
}
df = pd.DataFrame(retailer_dict); df

# Output
    id  gender  category
0   1   Men     western
1   2   Women   formal
2   3   Men     casual
3   1   Women   western
4   1   Men     formal
5   3   Women   casual


我想按ID分组,并将每个元素的计数显示为一个值。

到目前为止我尝试过的是:

df.groupby('id')['gender'].value_counts()

# Output
id  gender
1   Men       2
    Women     1
2   Women     1
3   Men       1
    Women     1
Name: gender, dtype: int64


也:

df.groupby('id')['gender'].apply(list)


但是我不知道如何对多个列执行相同的操作。

例:

# gives AttributeError
df.groupby('id')[['gender', 'category']].value_counts()

# Provides unuseful output
df.groupby('id')[['gender', 'category']].apply(list)
# Output
id
1    [gender, category]
2    [gender, category]
3    [gender, category]
dtype: object


预期产量:

id  gender                category
1   {Men: 2, Women:1}     {western: 2, formal:1}
2   {Women:1}             {formal:1}
3   {Men: 1, Women:1}     {casual: 2}


任何问题或其他建议将有所帮助。

最佳答案

GroupBy.aggvalue_counts一起使用并转换为dict

print (df.groupby('id')['gender', 'category'].agg(lambda x: x.value_counts().to_dict()))


要么:

from collections import Counter

print (df.groupby('id')['gender', 'category'].agg(lambda x: Counter(x)))




                    gender                     category
id
1   {'Men': 2, 'Women': 1}  {'western': 2, 'formal': 1}
2             {'Women': 1}                {'formal': 1}
3   {'Women': 1, 'Men': 1}                {'casual': 2}


如果需要再次用列表填充新列,请使用agg

print (df.groupby('id')['gender', 'category'].agg(list))
               gender                    category
id
1   [Men, Women, Men]  [western, western, formal]
2             [Women]                    [formal]
3        [Men, Women]            [casual, casual]


value_counts与多个列一起使用是有问题的,因为创建了具有两个列的值的MultiIndex第二级:

print (pd.concat([df.groupby('id')['gender'].value_counts(),
                  df.groupby('id')['category'].value_counts()]))

id  gender
1   Men        2
    Women      1
2   Women      1
3   Men        1
    Women      1
1   western    2
    formal     1
2   formal     1
3   casual     2
dtype: int64

关于python - Pandas Group通过单个列并显示多个列作为值计数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57818136/

10-12 22:46