简体   繁体   中英

Converting a list of dictionaries to dataframe

I have a list of dictionaries that I would like to convert to a dataframe. My list of dictionaries looks like this:

list_of_dicts = [{item1: 12}, 
{item2: 10},
{item3: 5},
{item4: 1}]

I am using the following code to convert to a dataframe:

dataframe = pd.DataFrame(list_of_dicts)

However the dataframe I get back is a diagonal

        0     1     2     3
item1   12   NaN   NaN   NaN
item2   NaN   10   NaN   NaN
item3   NaN   NaN   5    NaN
item4   NaN   NaN   NaN   1

I am interested in having the dataframe look like this:

index    item_num    value
0          item1     12
1          item2     10
2          item3     5
3          item4     1
dataframe = pd.DataFrame([tuple(k.items())[0] for k in list_of_dicts], columns=["item_num", "value"])

如果某个dict包含多个项目,即[...,{'item1.1':1, 'item1.2':2},...]

dataframe = pd.DataFrame([t for d in list_of_dicts for t in d.items()], columns=["item_num", "value"])

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM