PParker
PParker

Reputation: 1511

Transform a list including a dictionary into pandas dataframe

First I have a list like this:

lst = [['amazon', {'param_A': '789', 'param_B': '1234'}]]`

The first element always represents a shop.

I want to transform this list into a dataframe.

I think the easiest way to do this, would be to create a dictionary:

dicts={'shop':['amazon'],'param_A': ['789'], 'param_B': ['1234']}

Next step is: pd.DataFrame(dicts)

This way I get a dataframe where the keys of the dict are the column names.

enter image description here

How do I create a dictionary? Do you know a better way?

Upvotes: 1

Views: 32

Answers (1)

jezrael
jezrael

Reputation: 862681

Create list of dictionaries first and pass to DataFrame constructor:

lst = [['amazon', {'param_A': '789', 'param_B': '1234'}],
       ['amazon', {'param_A': '22', 'param_B': '1234'}]]

L = [{**{'shop': x[0]}, **x[1]} for x in lst]
#similar solution
L = [dict(shop=x[0], **x[1]) for x in lst]

df = pd.DataFrame(L)
print (df)
     shop param_A param_B
0  amazon     789    1234
1  amazon      22    1234

Upvotes: 1

Related Questions