简体   繁体   中英

Pandas grouping by and aggregating with respect to unique values

In pandas v 012, I have the dataframe below.

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

I can 'groupby' code as below:

c = df.groupby('code')

But, how can I get the unique texture occurences broken down with respect to code ? I tried this which gives an error:

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

From df given above, I want the result to be a dictionary, to be specific this one:

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

The size of my real df is quite large so I need the solution to be efficient / fast.

One way to get a dictionary of unique values is by applying pd.unique to the groupby object:

>>> 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)}

In newer versions of pandas unique is a method of groupby objects and so the neater way is:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM