Reputation: 31
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