是的,因为DataFrameGroupBy
没有to_dict
的属性,只有DataFrame
有to_dict
属性。
DataFrame.to_dict(outtype ='dict') 将DataFrame转换为字典。
你可以阅读更多关于DataFrame.to_dict
here
看看这个:
import pandas as pd
df = pd.DataFrame([np.random.sample(9), np.random.sample(9)])
df.columns = [c for c in 'abcdefghi']
# it will convert the DataFrame to dict, with {column -> {index -> value}}
df.to_dict()
{'a': {0: 0.53252618404947039, 1: 0.78237275521385163},
'b': {0: 0.43681232450879315, 1: 0.31356312459390356},
'c': {0: 0.84648298651737541, 1: 0.81417040486070058},
'd': {0: 0.48419015448536995, 1: 0.37578177386187273},
'e': {0: 0.39840348154035421, 1: 0.35367537180764919},
'f': {0: 0.050381560155985827, 1: 0.57080653289506755},
'g': {0: 0.96491634442628171, 1: 0.32844653606404517},
'h': {0: 0.682, 1: 0.0097104037581828839},
'i': {0: 0.66836630467152902, 1: 0.69104505886376366}}
type(df)
pandas.core.frame.DataFrame
# DataFrame.groupby is another type
type(df.groupby('a'))
pandas.core.groupby.DataFrameGroupBy
df.groupby('a').to_dict()
AttributeError: Cannot access callable attribute 'to_dict' of 'DataFrameGroupBy' objects, try using the 'apply' method
完美的作品像一个魅力非常感谢!出于某种原因,您构建pd.DataFrame的行会返回“dict”不可调用的错误。以防万一你想编辑它以供将来参考。 – Bastien 2014-10-31 23:29:16
这很奇怪,对我来说工作正常,而且看起来不像是一个错字......嗯。 – Ajean 2014-11-01 00:05:43
哦,废料,我只是再次测试它,它的工作。也许我第一次尝试时做错了什么。无论如何,再次感谢! – Bastien 2014-11-01 00:09:49