snowgirl11
snowgirl11

Reputation: 31

pandas - Is there a way to copy a value from one dataframe column to another based on a condition?

I have a dataframe that looks similar to this:

A     B                            
55    {'created by':Max,'id':22}   
38    {}                           
44    {'created by':John,'id':11}  

I want to create a new column that contains the 'id' value from Column B but if the dictionary is empty, it should copy the integer from Column A instead.

I have tried

df['C'] = [df.A[x] if df.B[x] == {} else df.B[x]['id'] for x in df]

but it returns a KeyError: 'id', which I believe is saying that there isn't a 'id' key? Wouldn't the if statement fix that??

I have also tried

df['C'] = [df.A if df.B[x] == {} else df.B[x]['id'] for x in df]

but that copies all column A as an object into each cell in Column C

Expected Result:

A    B                             C
55  {'created by':Max,'id':22}     22 
38  {}                             38
44  {'created by': John,'id':11}   11

Upvotes: 3

Views: 84

Answers (1)

BENY
BENY

Reputation: 323226

Let us try

df['C']=df.B.str.get('id').fillna(df.A)

Upvotes: 3

Related Questions