1

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:

enter image description here

How to write the code?

I use:

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

But it will get wrong. Could anyone help?

1
  • I have tried pd.DataFrame(dict),But it will show: If using all scalar values, you must pass an index Commented Jul 22, 2016 at 4:39

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

2 Comments

I have tried your method,But it will show: If using all scalar values, you must pass an index
@easyway Then the dictionary you gave as an example doesn't represent the dictionary your actual dictionary accurately. If it were the same form, that works in every version of pandas, AFAIK.
2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.