大熊猫分组和聚合独特的价值观

时间:2015-03-09 16:37:04

标签: python pandas dictionary dataframe unique

在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')

但是,如何针对texture分解出唯一的code出现的问题?我试过这个错误:

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的大小非常大,所以我需要有效/快速的解决方案。

1 个答案:

答案 0 :(得分:3)

获取唯一值字典的一种方法是将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()