Home > Net >  pandas - How to unstack dict column values to 2 new columns with the same name to all?
pandas - How to unstack dict column values to 2 new columns with the same name to all?

Time:02-08

I currently have the dataframe bellow, with a dict inside the column value.

     variable    value
0       b44     {55: 20}
1       a11     {56: 19}
5       a34     {33: 19}

How to transform the above df to a df that looks like this:

      variable    id   value
0       b44       55     20
1       a11       56     19
5       a34       33     19

CodePudding user response:

import pandas as pd
df = pd.DataFrame({'variable': ['b44', 'a11', 'a34'],'value': [{55: 20}, {56: 19}, {33: 19}]})
df = df.assign(**{'key': df.value.apply(lambda x: list(x.keys())[0]), 'value': df.value.apply(lambda x: list(x.values())[0])})

CodePudding user response:

Use list comprehension for list of tuples, DataFrame.pop is for extract column value for new ordering of columns names:

df[['id','value']] = [list(x.items())[0] for x in df.pop('value')]
print (df)
  variable  id  value
0      b44  55     20
1      a11  56     19
5      a34  33     19

Or:

df[['id','value']] = [(*x.keys(), *x.values()) for x in df.pop('value')]
print (df)
  variable  id  value
0      b44  55     20
1      a11  56     19
5      a34  33     19

CodePudding user response:

Try with stack after create the new df

s = pd.DataFrame(df.pop('value').tolist(),index=df.index).stack().reset_index(level=1)
s.columns = ['id','value']
df = df.join(s)
df
Out[82]: 
  variable  id  value
0      b44  55   20.0
1      a11  56   19.0
5      a34  33   19.0

CodePudding user response:

You can use the apply function :

df['id'] = df.values.apply(lambda x: list(x.keys())[0])
df['value'] = df.values.apply(lambda x: list(x.values())[0])
  •  Tags:  
  • Related