Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flatten pandas dataframe

Tags:

python

pandas

Here is my pandas dataframe, and I would like to flatten. How can I do that ?

The input I have

key column
1 {'health_1': 45, 'health_2': 60, 'health_3': 34, 'health_4': 60, 'name': 'Tom'}   
2 {'health_1': 28, 'health_2': 10, 'health_3': 42, 'health_4': 07, 'name': 'John'}  
3 {'health_1': 86, 'health_2': 65, 'health_3': 14, 'health_4': 52, 'name': 'Adam'}

The expected output

All the health and name will become a column name of their own with their corresponding values. In no particular order.

health_1 health_2 health_3 health_4 name key
45          60       34       60    Tom  1
28          10       42       07    John 2
86          65       14       52    Adam 3
like image 745
PolarBear10 Avatar asked Dec 10 '22 04:12

PolarBear10


2 Answers

You can do it with one line solution,

df_expected = pd.concat([df, df['column'].apply(pd.Series)], axis = 1).drop('column', axis = 1)

Full version:

import pandas as pd
df = pd.DataFrame({"column":[
{'health_1': 45, 'health_2': 60, 'health_3': 34, 'health_4': 60, 'name': 'Tom'}   ,
{'health_1': 28, 'health_2': 10, 'health_3': 42, 'health_4': 7, 'name': 'John'}  ,
{'health_1': 86, 'health_2': 65, 'health_3': 14, 'health_4': 52, 'name': 'Adam'}
]})

df_expected = pd.concat([df, df['column'].apply(pd.Series)], axis = 1).drop('column', axis = 1)
print(df_expected)

DEMO: https://repl.it/repls/ButteryFrightenedFtpclient

like image 158
Always Sunny Avatar answered Jan 22 '23 01:01

Always Sunny


This should work:

df['column'].apply(pd.Series)

Gives:

   health_1  health_2  health_3  health_4  name
0  45        60        34        60        Tom 
1  28        10        42        7         John
2  86        65        14        52        Adam
like image 27
BhishanPoudel Avatar answered Jan 22 '23 00:01

BhishanPoudel