按唯一值分组和聚合

2024-05-16 11:45:54 发布

您现在位置:Python中文网/ 问答频道 /正文

在pandasv012中,我有下面的数据帧。你知道吗

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


Tags: iddfcodetriangularonepdsoftthree
1条回答
网友
1楼 · 发布于 2024-05-16 11:45:54

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

在较新的熊猫版本中,uniquegroupby对象的一种方法,因此更简洁的方法是:

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

相关问题 更多 >