How to convert a dict to a dataframe, with the values as headers and rows?

Viewed 109

So I've recently run into a return from an API call where the return format is a list of dictionaries but the formatting causes the pd.DataFrame() to come out wrong. I get a return format of:

{'name': 'a1', 'value': 'b1'}
{'name': 'a2', 'value': 'b2'}
{'name': 'a3', 'value': 'b3'}
{'name': 'a4', 'value': 'b4'}
{'name': 'a5', 'value': 'b5'}

When i run pd.DataFrames on this is turns into:

name    value
a1      b1
a2      b2
a3      b3
a4      b4
a5      b5

I have tried using df.pivot(column='name', values='value') but that leads to a 5 x 5 df instead of just 1 row. Ideally I would like to get it where the column names= dictionary[name] and the row value=dictionary[value]:

index a1  a2  a3  a4  a5
0     b1  b2  b3  b4  b5

Any help and suggestions are greatly appreciated, thanks!

1 Answers

Set the index to the "name" column, and then transpose the dataframe (to switch rows and columns)

df = pd.DataFrame(api_result)
df = df.set_index("name").T

You can also do this directly when creating the dataframe, using the from_records method:

df = pd.DataFrame.from_records(api_result, index="name").T
Related