bowlingpolar
bowlingpolar

Reputation: 13

Pandas - Return key from a column that looks like a dictionary

I have a dataframe in pandas that looks like this

A B
data {"foo":"bar","cat":"dog"}
data1 {"foo":"car","cat":"log"}

I don't think that the data in column B is actually a dictionary, but it looks like one. I'm trying to create a new column, C, with the value for "cat" for each row, so my desired output would be the same table as above, with a new column C appended to the end, like this

C
dog
log

I've tried the following:

I understand that my general issue is that i'm trying to use attributes that don't work with my data type, but am not sure what else to try. any ideas?

Upvotes: 1

Views: 237

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195438

You can use ast.literal_eval to parse the string to standard python dictionary and then use dict.get to get the value:

from ast import literal_eval

df["C"] = df["B"].apply(lambda x: literal_eval(x).get("cat"))
print(df)

Prints:

       A                          B    C
0   data  {"foo":"bar","cat":"dog"}  dog
1  data1  {"foo":"car","cat":"log"}  log

Upvotes: 0

Related Questions