Home > database >  Convert data in format [{index:value}] to a dataframe
Convert data in format [{index:value}] to a dataframe

Time:01-04

I have some data in the following format

[{'a':1}, {'b':2}, {'c':3}]

Is there a way to convert it into a dataframe with {index: value}

  value
a  1
b  2
c  3

I've tried combinations of the pandas dataframe constructor without success.

  • pd.DataFrame()
  • pd.DataFrame.from_dict()
  • pd.DataFrame.from_records()

CodePudding user response:

A list of dictionaries is not an ideal format to have your data stored for the purpose of creating a Dataframe, but if each dictionary has only one item, you can try the following:

data = [{'a': 1}, {'b': 2}, {'c': 3}]
pd.DataFrame(data=[list(x.values())[0] for x in data], index=[list(x.keys())[0] for x in data])

CodePudding user response:

tuple and dataframe. Code below

pd.DataFrame(tuple(k)).stack().to_frame('Value').droplevel(level=0)



    Value
a    1.0
b    2.0
c    3.0

CodePudding user response:

One way is to convert your data to an appropriate dict format that pandas can understand

import pandas as pd

data = [{'a':1}, {'b':2}, {'c':3}]
data = {k: v for d in data for k, v in d.items()}

pd.DataFrame.from_dict(data=data, orient='index', columns=['value'])

or of course

data = [{'a':1}, {'b':2}, {'c':3}]

pd.DataFrame.from_dict(
    data={k: v for d in data for k, v in d.items()},
    orient='index', columns=['value']
)

Please notice that this only works when you have no duplicate keys among those dicts in your list. If your data looks like the following, then you should consider the solutions provided by @Derek O or @wwnde

data = [{'a':1}, {'b':2}, {'c':3}, {'c':4}]

CodePudding user response:

Here's one more way: The idea is to fill NaN values with same values from back and front and just take one column:

df = pd.DataFrame(lst).bfill().ffill().T[[0]].set_axis(['value'], axis=1).astype(int)

Output:

   value
a      1
b      2
c      3
  •  Tags:  
  • Related