0

I have a data like this,

     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

I want OP :

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

Here is code I have tried,

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

How to achieve this?

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
MMMMS
  • 2,179
  • 9
  • 43
  • 83

2 Answers2

5

I believe need to_dict with l for lists:

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]}

If order important add parameter into for 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])])
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • why did you create the ordered dictionary? Can you show the difference in the iteration process – Golden Lion Sep 23 '20 at 11:39
  • @GoldenLion - ya, in oldier python version. In last versions dicts are changes, [link](https://stackoverflow.com/questions/1867861/how-to-keep-keys-values-in-same-order-as-declared) so not sure if now are usable. (like few years ago) – jezrael Sep 23 '20 at 11:42
  • @GoldenLion - I use `OrderDict`, because in old dicionaries was not declared order of keys. – jezrael Sep 23 '20 at 11:43
  • OrderedDict([(0, ['Friday', 136, 239, 0, 0]), (1, ['Monday', 305, 431, 0, 0]), (2, ['Saturday', 0, 3, 0, 0])]) show how to parse this data – Golden Lion Sep 23 '20 at 13:44
0

Overview: I show how to iteriate the dictionary items using a list comprehension

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]
Golden Lion
  • 3,840
  • 2
  • 26
  • 35