简体   繁体   中英

pandas DataFrame.from_dict doesn't result the right multiIndex where the keys of dict are tuple

When I want to transform a dict with tuple keys into a dataframe with multi-index, I used pandas.DataFrame.from_dict method. But I fund the result seems to be wrong. Here is my code:

dict_var1 = Counter({('w1', 's1'): 47, ('w2', 's1'): 40, ('w3', 's2'): 35, ('w1', 's3'): 30, ('w4', 's4'): 28})
frame_var1 = pd.DataFrame.from_dict(dict_var1, orient='index', columns=['num'])
print(frame_var1)

And the result is:

  num (w1, s1) 47 (w2, s1) 40 (w3, s2) 35 (w1, s3) 30 (w4, s4) 28 

The index of the frame is not multi-level. I feel confused about the result very much. Can anyone comment: 1. Why does this function get this result? 2. How can I achieve my goals?

Hope for reply. Thanks very much.

Create Series with MultiIndex and for one column DataFrame use Series.to_frame :

frame_var1 = pd.Series(dict_var1).to_frame('num')
print(frame_var1)

       num
w1 s1   47
w2 s1   40
w3 s2   35
w1 s3   30
w4 s4   28

Another solution is create MultiIndex by tuples with MultiIndex.from_tuples :

mux = pd.MultiIndex.from_tuples(dict_var1.keys())
frame_var1 = pd.DataFrame(list(dict_var1.values()), index=mux, columns=['num'])

print(frame_var1)

       num
w1 s1   47
w2 s1   40
w3 s2   35
w1 s3   30
w4 s4   28

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