Bussiere
Bussiere

Reputation: 1152

Replace each cell in a dataframe by the value of a dict inside each cell pandas

Here is my dataframe :

df2

0   1   2   3   4   5   

0   {'tag_name': 'fre'}     {'tag_name': 'bgs'}     {'tag_name': 'fa'}  {'tag_name': 'cu'}  {'tag_name': 'bi'}
1   {'tag_name': 'fr2e'}    {'tag_name': 'b1gs'}    {'tag_name': 'f3'}  {'tag_name': 'czu'}     {'tag_name': 'bRi'}

So i would like for each cell to have the value of ['tag_name'] inside and not the dict.

thanks and regards

Upvotes: 0

Views: 84

Answers (1)

AndreyF
AndreyF

Reputation: 1838

How about this:

df2 = df2.apply(lambda axis: [axis[0]] + [x['tag_name'] for x in axis[1:]], axis=1)

Or like suggested with type check:

df2 = df2.apply(lambda axis: [x['tag_name'] if type(x) == dict else x for x in axis], axis=1)

Upvotes: 1

Related Questions