Home > Back-end >  Convert dictionary keys and values into rows and columns
Convert dictionary keys and values into rows and columns

Time:08-02

I have a list of dictionaries with multiple rows. I need to store the keys as columns and value as rows.

    date        model
    22/01/2022  [{'vehicles': {'engine': 0, 'status': 5, 'size': 0, 'warranty': 2, 'type': 3, }}]
    .
    .
    .
    23/01/2022  [{'vehicles': {'engine': 3, 'status': 4, 'size': 1, 'warranty': 5, 'type': 1, }}]

df = pd.DataFrame.from_dict(df["model"]['vehicles'], orient="columns")

I tired to select the values but its not working.

CodePudding user response:

df = pd.DataFrame({'date': ['22/01/2022', '23/01/2022'], 'model': [[{'vehicles': {'engine': 0, 'status': 5, 'size': 0, 'warranty': 2, 'type': 3, }}], [{'vehicles': {'engine': 3, 'status': 4, 'size': 1, 'warranty': 5, 'type': 1, }}]]})
df = df.explode('model')
df.model = [m['vehicles'] for m in df.model]
pd.concat([df, df.model.apply(pd.Series)], axis=1).drop('model', axis=1)

Output:

         date  engine  status  size  warranty  type
0  22/01/2022       0       5     0         2     3
1  23/01/2022       3       4     1         5     1
  • Related