I have a dictionary:
{'1': -1.4, '8': -6.04, '6': 0.75}
I want to convert this to a dataframe that looks like:
code score
1 -1.4
8 -6.04
6 0.75
CodePudding user response:
You can use pd.Dataframe()
, as follows:
d = {'1': -1.4, '8': -6.04, '6': 0.75}
df = pd.DataFrame({'code': d.keys(), 'score': d.values()})
or use pd.Series
.reset_index()
:
d = {'1': -1.4, '8': -6.04, '6': 0.75}
df = pd.Series(d).rename_axis(index='code').reset_index(name='score')
Result:
print(df)
code score
0 1 -1.40
1 8 -6.04
2 6 0.75
CodePudding user response:
Another way:
d = {'1': -1.4, '8': -6.04, '6': 0.75}
df = pd.DataFrame.from_dict(d, orient='index', columns=['score']) \
.rename_axis('code') \
.reset_index()
Output:
>>> df
code score
0 1 -1.40
1 8 -6.04
2 6 0.75
CodePudding user response:
The generic code to convert JSON to any number of columns dataframe
data={'1': -1.4, '8': -6.04, '6': 0.75}
df=pd.DataFrame([data]).T.reset_index() # create dataframe and transpose it
df.columns=['code', 'score'] # set the column names
Result:
code score
0 1 -1.40
1 8 -6.04
2 6 0.75