3

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

1 Answer 1

3

Let us try

df['C']=df.B.str.get('id').fillna(df.A)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.