【问题标题】:Pandas grouping by and aggregating with respect to unique valuesPandas 按唯一值分组和聚合
【发布时间】:2015-03-09 16:37:04
【问题描述】:

在 pandas v 012 中,我有下面的数据框。

import pandas as pd
df = pd.DataFrame({'id' : range(1,9),
                        'code' : ['one', 'one', 'two', 'three',
                                    'two', 'three', 'one', 'two'],
                        'colour': ['black', 'white','white','white',
                                'black', 'black', 'white', 'white'],
                        'texture': ['soft', 'soft', 'hard','soft','hard',
                                            'hard','hard','hard'],
                        'shape': ['round', 'triangular', 'triangular','triangular','square',
                                            'triangular','round','triangular'],
                        'amount' : np.random.randn(8)},  columns= ['id','code','colour', 'texture', 'shape', 'amount'])

我可以'groupby'code如下:

c = df.groupby('code')

但是,我怎样才能得到与 code 相关的唯一 texture 出现次数?我试过这个,它给出了一个错误:

question = df.groupby('code').agg({'texture': pd.Series.unique}).reset_index()
#error: Must produce aggregated value

从上面给出的df,我希望结果是一个字典,具体来说是这个:

result = {'one':['soft','hard'], 'two':['hard'], 'three':['soft','hard']}

我真正的df 的大小非常大,所以我需要高效/快速的解决方案。

【问题讨论】:

    标签: python pandas dictionary dataframe unique


    【解决方案1】:

    获取唯一值字典的一种方法是将pd.unique 应用于groupby 对象:

    >>> df.groupby('code')['texture'].apply(pd.unique).to_dict()
    {'one': array(['hard', 'soft'], dtype=object),
     'three': array(['hard', 'soft'], dtype=object),
     'two': array(['hard'], dtype=object)}
    

    较新 版本的 pandas 中,uniquegroupby 对象的方法,因此更简洁的方法是:

    df.groupby("code")["texture"].unique()
    

    【讨论】:

    • 谢谢,apply 版本确实有效,但不是直接的unique() 版本。
    • 糟糕,没有注意到 OP 使用的是旧版本,即使它就在第一句话中。 :-/
    猜你喜欢
    • 1970-01-01
    • 2020-09-08
    • 1970-01-01
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    • 2013-02-03
    • 1970-01-01
    • 2022-01-26
    相关资源
    最近更新 更多