简体   繁体   中英

How to convert stacked dataframe to dictionary in pandas?

I have stacked dataframe as below. I tried to convert to the dictionary using to_dict() command. However, I got the following error.

TypeError: key ('PODIUM WINDOW', 'SHGC value') is not a string  

Can anyone tell me what should I do further for this stacked dataframe to convert to the dictionary as below?

[{"Construction":"Office Window","U-value[W/m2-K]":1.63},{"Construction":"Office Window","SHGC value":0.22},{"Construction":"Podium Window","U-value[W/m2-K]":5.48},{"Construction":"Podium Window","SHGC value":0.70}]

stacked dataframe

Construction
OFFICE WINDOW  U-value[W/m2-K]    1.63
               SHGC value         0.22
PODIUM WINDOW  U-value[W/m2-K]    5.48
               SHGC value         0.70

Reshape by unstack , create column from index by reset_index and last call DataFrame.to_dict :

d = df.unstack().reset_index().to_dict(orient='records')
print (d)

[{'Construction': 'OFFICE WINDOW', 'SHGC value': 0.22, 'U-value[W/m2-K]': 1.63}, 
 {'Construction': 'PODIUM WINDOW', 'SHGC value': 0.7, 'U-value[W/m2-K]': 5.48}]

EDIT: Use list comprehension with dictionary by contructor:

d = [{'Construction': i, j:k} for (i, j), k in df.items()]
print (d)

[{'Construction': 'OFFICE WINDOW', 'U-value[W/m2-K]': 1.63}, 
 {'Construction': 'OFFICE WINDOW', 'SHGC value': 0.22}, 
 {'Construction': 'PODIUM WINDOW', 'U-value[W/m2-K]': 5.48}, 
 {'Construction': 'PODIUM WINDOW', 'SHGC value': 0.7}]

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