簡體   English   中英

大熊貓分組和聚合獨特的價值觀

[英]Pandas grouping by and aggregating with respect to unique values

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

獲取唯一值字典的一種方法是將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中, unique是一種groupby對象的方法,因此更簡潔的方法是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM