简体   繁体   中英

Pandas, list of dictionaries where values are a list. Convert dictionary keys into column names. Convert each element in value list to a row

I have a list of dictionaries where the values are another list

[ {111: [1, 2, 3]}, {112:[4, 5, 6]}, {113:[7,8,9]}]

I would like to put them in a pandas dataframe such that the dictionary keys are the column names, and each element in the list has it's own row

So

df

111    112    113
1        4         7
2        5         8
3        6        9

IIUC, you can write a list comprehension and concat your dataframe axis wise.

import pandas as pd
d = [ {111: [1, 2, 3]}, {112:[4, 5, 6]}, {113:[7,8,9]}]

df = pd.concat([pd.DataFrame.from_dict(inner_dict,orient='columns') for inner_dict in d],axis=1)

print(df)

   111  112  113
0    1    4    7
1    2    5    8
2    3    6    9

Give collections.ChainMap a try:

from collections import ChainMap

d = [{111: [1, 2, 3]}, {112:[4, 5, 6]}, {113:[7,8,9]}]
df = pd.DataFrame({**ChainMap(*d[::-1])})

Out[79]:
   111  112  113
0    1    4    7
1    2    5    8
2    3    6    9
import pandas as pd
a  = [ {111: [1, 2, 3]}, {112:[4, 5, 6]}, {113:[7,8,9]}]

for item in a:
    for k, v in item.items():
        df[k] = v

df

    111 112 113
0   1   4   7
1   2   5   8
2   3   6   9

Maybe this one using a dict comprehension?

data = [{ 111: [1, 2, 3] }, { 112: [4, 5, 6] }, { 113: [7,8,9] }]
pd.DataFrame({ title: values for column in data for title, values in column.items() })

But you probably would be better off having your data stored as a { title: [value] } dict which pandas can recognize right away.

data = { 111: [1, 2, 3], 112: [4, 5, 6], 113: [7, 8, 9] }
pd.DataFrame(data)

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