简体   繁体   中英

Dict of Dict from Pandas DataFrame with dates

I have the following pandas dataframe:

date       AAC      AFE     AFS     AKD    MAF   PRE                                    
2020-04-05  0       10000   0       0      0     75000
2020-04-06  0       30000   10000   0      0     0  
2020-04-10  47000   33000   20000   0      2000  8700
2020-04-11  0       0   0   0       25000  0     0  
2020-04-16  0       0   0   0       50000  0     0  
2020-04-21  0       30000   25000   0   0  1000  0  
2020-04-30  0       122000  65000   0   0  1000  0  

I am trying to create a dict of dict so that the resulting dictionary resembles the following format

{'2020-04-05': {'AAC': 0, 'AFE': 10000, 'AFS': 0, etc}
 '2020-04-06': {AAC: 0, 'AFE': 30000, 'AFS': 10000, etc}} 

My current solution:

d = {date: {col: df[col].values for col in df.columns} for date in demand_df.index}

yields the wrong (column-wise/axis 1) results as I am not getting the correct value, per product per date

Any help much appreciated!

you can use to_dict with orient=index after set_index the column 'date':

print (df.set_index('date').to_dict(orient='index'))
{'2020-04-05': {'AAC': 0, 'AFE': 10000, 'AFS': 0, 'AKD': 0, 'MAF': 0, 'PRE': 75000}, 
 '2020-04-06': {'AAC': 0, 'AFE': 30000, 'AFS': 10000, 'AKD': 0, 'MAF': 0, 'PRE': 0}, 
 '2020-04-10': {'AAC': 47000, 'AFE': 33000, 'AFS': 20000, 'AKD': 0, 'MAF': 2000, 'PRE': 8700}, ...}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM