Home > Back-end >  How to separate dictionary in data frame each in one column and only keep the value without the key
How to separate dictionary in data frame each in one column and only keep the value without the key

Time:11-08

I have a data frame contains columns of dictionaries has few items inside it, i wanat seperate each value in one column and keep only the value.

right now like this

0 {'_id': '1', 'value': 'apple'} 1 {'_id': '2', 'value': 'car'}

dic
{'_id': '1', 'value': 'apple'}
{'_id': '2', 'value': 'car'}

I want them to be like this

first value second value
1 apple
2 car

CodePudding user response:

Just apply pandas.Series on that column:

>>> df = df['dic'].apply(pd.Series)
>>> df
  _id  value
0   1  apple
1   2    car

Then change the column names if needed:

>>> df.columns = ['first value', 'second value']
>>> df
  first value second value
0           1        apple
1           2          car

Or, you can just pass the same index with a lambda function:

>>> df['dic'].apply(lambda x:pd.Series(x.values(), ['first value', 'second value']))
  first value second value
0           1        apple
1           2          car
  • Related