[英]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.