【问题标题】:Python & pandas: how to group in a nonstandard wayPython & pandas:如何以非标准方式分组
【发布时间】:2018-04-12 02:35:31
【问题描述】:

我知道基本的 pandas 功能,但我不清楚在这种情况下如何分组。

我有一个包含各种水果及其特征列表的数据框:

fruit    x1      x2
apple    red     sweet
apple    yellow  sweet
apple    green   tart
apple    red     sweet
apple    red     sweet

我怎么能像这样总结每个水果(苹果之后还有更多)?

3 个苹果:又红又甜
1个苹果:黄而甜
1 个苹果:绿色和酸味

我查看了 groupby,尝试了 apply 函数,并查看了 pandas 文档,但这让我无法理解。

有什么想法吗?非常感谢。

【问题讨论】:

标签: python pandas dataframe


【解决方案1】:

Counter

import pandas as pd
from collections import Counter

pd.Series(Counter(map(tuple, df.values)))

apple  green   tart     1
       red     sweet    3
       yellow  sweet    1
dtype: int64

pd.factorizenp.bincount

i, r = pd.factorize(list(map(tuple, df.values)))
pd.Series(dict(zip(r, np.bincount(i))))

apple  green   tart     1
       red     sweet    3
       yellow  sweet    1
dtype: int64

【讨论】:

    【解决方案2】:

    你可以试试下面的:

    df['count']=0
    group_df = df.groupby(["fruit","x1","x2"])['count'].count().reset_index()
    

    输出如下:

       fruit      x1     x2  count
    0  apple   green   tart      1
    1  apple     red  sweet      3
    2  apple  yellow  sweet      1
    

    当然,您可以在此之后连接列以使其完全符合您所需的输出。

    如果你想对计数进行排序:

    group_df = df.groupby(["fruit","x1","x2"])['count'].count().reset_index().sort_values(by=['count'],ascending=False)
    

    【讨论】:

      猜你喜欢
      • 2019-11-24
      • 2016-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-08
      • 1970-01-01
      • 2013-05-11
      • 1970-01-01
      相关资源
      最近更新 更多