Reputation: 56
So I have a DataFrame like this
df = pd.DataFrame([
[dict(F='y', G='v'),'F'],
[dict(F='y', G='v'),'G'],
], columns=list('AB'))
I need to generate a new column C, based on column B and get sth like this
pd.DataFrame([
[dict(F='y', G='v'),'F','y'],
[dict(F='y', G='v'),'G','v'],
], columns=list('ABC'))
I am thinking of using apply function, but failed
Upvotes: 1
Views: 39
Reputation: 863541
Use .get
method for possible get default value if no match:
df['C'] = df.apply(lambda x: x['A'].get(x['B']), axis=1)
#if values always match
#df['C'] = df.apply(lambda x: x['A'][x['B']], axis=1)
print (df)
A B C
0 {'F': 'y', 'G': 'v'} F y
1 {'F': 'y', 'G': 'v'} G v
Upvotes: 1