Home > database >  Extract list from column pandasa that contains JSON
Extract list from column pandasa that contains JSON

Time:03-24

I have a df that looks like this

           id                    value
   USDC_Astar {'CELR': 0.31,'PIO':0.1}
USDC_Ethereum            {'MM': 0.04,}

I want to extract a list from the column value that looks like this:

l = ['CELR', 'PIO', 'MM]

I am trying to use the function .str.extract() but without success

CodePudding user response:

Use ast.literal_eval:

import ast

# if 'value' column contains string representation of dict
l = df['value'].apply(ast.literal_eval).explode().to_list()

# if 'value' column already contain dict
l = df['value'].explode().to_list()

Output:

>>> l
['CELR', 'PIO', 'MM']

CodePudding user response:

Simple solution without ast

x=[]

[x.extend(v) for v in df['values']]

print(x)

['CELR', 'PIO', 'MM']

  • Related