Home > Back-end >  How to transform a list of dictionary into a table
How to transform a list of dictionary into a table

Time:04-30

How to transform a list of dictionary into a table.

Here is the table:

[{'wow': 1,
  'item': 1,
  'money': 1},
 {'best': 1,
  'sock': 1,
  'saved': 1,
  'found': 1},
 {'cry': 1,
  'shock': 1,
  'sound': 1}]

Desired ouput:

words n
wow 1
item 1
... ...

I have tried

pd.DataFrame(x , columns=['Words', 'n'])

However, the output that I receive is just an index with empty columns.

Any help?

CodePudding user response:

You can use pandas melt

x = [{'wow': 1,
  'item': 1,
  'money': 1},
 {'best': 1,
  'sock': 1,
  'saved': 1,
  'found': 1},
 {'cry': 1,
  'shock': 1,
  'sound': 1}]

df = pd.DataFrame(x)
df = df.melt().dropna().reset_index(drop=True)
df.columns = ['words', 'n']

Output:

enter image description here

CodePudding user response:

You can use pd.columns

An example which you can refer to:

df = pd.DataFrame(someInput)
headers = ["Words", "n"]
df.columns = headers

CodePudding user response:

You can do it this way:

input_dicts = [{'wow': 1,
                    'item': 1,
                    'money': 1},
                   {'best': 1,
                    'sock': 1,
                    'saved': 1,
                    'found': 1},
                   {'cry': 1,
                    'shock': 1,
                    'sound': 1}]
    cols = [[], []]
    for d in input_dicts:
        cols[0].extend(list(d.keys()))
        cols[1].extend(list(d.values()))
    df = pd.DataFrame({"col_name_1": cols[0], "col_name_2": cols[1]})

CodePudding user response:

Chaining items of these dictionaries to build may meet your requirements:

>>> x = [{'wow': 1,
...   'item': 1,
...   'money': 1},
...  {'best': 1,
...   'sock': 1,
...   'saved': 1,
...   'found': 1},
...  {'cry': 1,
...   'shock': 1,
...   'sound': 1}]
>>> from itertools import chain
>>> pd.DataFrame(chain.from_iterable(d.items() for d in x), columns=['words', 'n'])
   words  n
0    wow  1
1   item  1
2  money  1
3   best  1
4   sock  1
5  saved  1
6  found  1
7    cry  1
8  shock  1
9  sound  1

CodePudding user response:

You could just chain the .items() while constructing the dataframe:

records = [
    {'wow': 1, 'item': 1, 'money': 1},
    {'best': 1, 'sock': 1,'saved': 1, 'found': 1},
    {'cry': 1, 'shock': 1, 'sound': 1}
]

df = pd.DataFrame((item for record in records for item in record.items()),
                  columns=["Word", "n"])

Result:

    Word  n
0    wow  1
1   item  1
2  money  1
3   best  1
4   sock  1
5  saved  1
6  found  1
7    cry  1
8  shock  1
9  sound  1

CodePudding user response:

I hope this code help

  tbl = [{'wow': 1, 'item': 1, 'money': 1}, {'best': 1, 'sock': 1, 'saved': 1, 'found': 1}, {'cry': 1, 'shock': 1, 'sound': 1}] 
  dicts = {}
  for d in tbl:
    dicts.update(d)

  df = pd.DataFrame.from_dict(dict(word=list(dicts.keys()), n=list(dicts.values())))
  • Related