GroupBy - Python

时间:2018-05-03 08:50:33

标签: python python-3.x pandas

我有这样的数据,

     dayname          A         B              C           D         E

0     Friday        136.0      239.0          0.0        0.0      283.0   
1     Monday        305.0      431.0          0.0        0.0      845.0   
2   Saturday          0.0        3.0          0.0        0.0       11.0

我想要OP:

 {
    'Friday' :[136, 239, 0, 283],
    'Monday' :[305, 431, 0, 845],
    'Saturday' :[0, 3, 0, 11]
 }

这是我尝试过的代码,

output =  (pd.DataFrame(df).groupby(['dayname','areaName'])['avgCount'].sum().unstack(fill_value=0).rename_axis(None, 1).reset_index())
print(output)
ot = pd.DataFrame(output)
#ot contains the above mentioned data

如何实现这一目标?

2 个答案:

答案 0 :(得分:4)

我认为对The entity type DbEntityEntry is not part of the model for the current context s l list需要to_dict

df = df.set_index('dayname').T.to_dict('l')
print (d)
{'Friday': [136.0, 239.0, 0.0, 0.0, 283.0], 
 'Monday': [305.0, 431.0, 0.0, 0.0, 845.0], 
 'Saturday': [0.0, 3.0, 0.0, 0.0, 11.0]}

如果订单重要,请为into添加参数OrderedDict

from collections import OrderedDict
d = df.set_index('dayname').T.to_dict('l', into=OrderedDict)
print (d)
OrderedDict([('Friday', [136.0, 239.0, 0.0, 0.0, 283.0]), 
             ('Monday', [305.0, 431.0, 0.0, 0.0, 845.0]), 
             ('Saturday', [0.0, 3.0, 0.0, 0.0, 11.0])])

答案 1 :(得分:0)

概述:我展示了如何使用列表理解来迭代字典项

dayname=['Friday','Monday','Saturday']
A=[136,305,0]
B=[239,431,3]
C=[0,0,0]
D=[0,0,0]
E=[283,845,11]
df=pd.DataFrame({'dayname':dayname,'A':A,'B':B,'C':C,'D':D})
df.set_index('dayname')
new_df=df.T
#l for list
#result=new_df.to_dict('l', into=OrderedDict)
result=df.set_index('dayname').T.to_dict('l')

for key,value in result.items():
   print (key)
   [print(item) for item in value]