access value from dict stored in python df
Hi I want to access a value from a dictionary stored in a dataframe column and export it to a list.
I can do it by splitting it as a string, like this
# dataframe
df = pd.DataFrame(data={'a':[{'word' : '3'}, {'word':'1'}, {'word':'0'}], 'b':['cat', 'dog', 'mouse']})
# get the number value as a string
idx = df['a'].astype(str).str[10].to_list()
but i thought it might be nicer to treat it as an actual dictionary and access via the dictionary item. However when I create the list via df['a'].items() the list stores the number inside a dict_values(['x']) string which I dont want to have, I just want [3,1,0].
# get the number value as a dictionary item
[i[1].values() for i in df['a'].items()]
all suggestions welcome. thank you
Solution 1:
You can use Series.str.get
to extract values from an object
column with dictionaries in it.
df['idx'] = df['a'].str.get('word')
indices = df['idx'].to_list()
Solution 2:
Another option is to convert the column to a list, cast it to a DataFrame constructor. This creates a DataFrame where the columns correspond to dictionary keys and values correspond to dict values. Then simply select the relevant column/key and convert the values to list:
idx = pd.DataFrame(df['a'].tolist())['word'].tolist()
Output:
['3', '1', '0']