Reputation: 11895
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.
Upvotes: 1
Views: 102
Reputation: 176820
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()
Upvotes: 3