【发布时间】:2015-03-09 16:37:04
【问题描述】:
在 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 的大小非常大,所以我需要高效/快速的解决方案。
【问题讨论】:
标签: python pandas dictionary dataframe unique