I have a python dictionary,dict1 where keys are integer & values are string. I want to create a pandas data frame with this dictionary.Can you please suggest me how to do that in python 3.X?
I used following code
df_i=pd.DataFrame(dict1,columns=['num_int','num_str'])
But got error message
ValueError: If using all scalar values, you must pass an index
I also tried the steps mentioned in here but I got output like
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,...
for all the rows
My sample dictionary looks like
1: '031155233',
2: '031420399',
3: '031442593',
4: '032952341',
5: '033141410',
6: '033404365',
7: '033423523',
8: '033461055',
9: '012025663',
10: '012322156',
11: '021422395',
12: '036145459',
13: '035910162',
14: '042144641',
15: '042525232',
16: '040535923',
17: '042523604',
18: '029090230',
19: '012402315',
I think you should just add orient = 'index'
when calling pd.DataFrame.from_dict()
my_dict = {1: '031155233',
2: '031420399',
3: '031442593'}
>>> pd.DataFrame.from_dict(my_dict, orient='index')
0
1 031155233
2 031420399
3 031442593
And if you need to pass in the column names you mention, here's a way :
df = pd.DataFrame.from_dict(my_dict, orient='index').reset_index()
df.columns = ['num_int','num_str']
>>> print(df)
num_int num_str
0 1 031155233
1 2 031420399
2 3 031442593
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.