Home > other >  Retrieving a list from a specific value with a dictionnary as column type
Retrieving a list from a specific value with a dictionnary as column type

Time:03-17

I'm working with a pandas DataFrame and one of the column is a dictionary. I need to retrieve a list which contains the value corresponding to a specific key for each row of the DataFrame.

df = pd.DataFrame({
    'col1': [{'id': 1, 'value': 3}, {'id': 2, 'value': 25}]
})

                     col1
0   {'id': 1, 'value': 3}
1  {'id': 2, 'value': 25}

I managed to get the desired output using the apply() method and a lambda function creating a new column and filling it with the said value for each row, and then taking this Series as list and deleting the temporary column. Is there an easier way to do this?

For this sample data, the output would be

[3, 25]

CodePudding user response:

.str, despite its name, works for lists and objects in addition to strings:

vals = df['col1'].str['value']

Output:

>>> vals
0     3
1    25
Name: col1, dtype: int64

>>> vals.tolist()
[3, 25]
  • Related