简体   繁体   中英

How to create pandas dataframe from python dictionary?

I have a python dictionary below:

dict = {'stock1': (5,6,7), 'stock2': (1,2,3),'stock3': (7,8,9)};

I want to change dictionary to dataframe like:

在此处输入图片说明

How to write the code?

I use:

pd.DataFrame(list(dict.iteritems()),columns=['name','closePrice'])

But it will get wrong. Could anyone help?

You are overcomplicating the problem, just pass your dictionary into the DataFrame constructor:

import pandas as pd

d = {'stock1': (5,6,7), 'stock2': (1,2,3),'stock3': (7,8,9)}
print(pd.DataFrame(d))

Prints:

   stock1  stock2  stock3
0       5       1       7
1       6       2       8
2       7       3       9

Try this: Do not name your variables python key words!

dd = {'stock1': (5,6,7), 'stock2': (1,2,3),'stock3': (7,8,9)};
#pd.DataFrame(dd) Should work!

pd.DataFrame.from_dict(dd, orient='columns')

   stock1  stock2  stock3
0       5       1       7
1       6       2       8
2       7       3       9

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