Pandas: How to Convert Column to List Then Use Explode Function

Viewed 49

I have a dataframe like this:

product_name                                            price                                                    variations
Cream Deluxe Gold (615g)    [ '130.00', '255.00', '500.00', '995.00', '8200.00']          [ '6 PIECES', '12 PIECES', '24 PIECES', '48 PIECES', '1 PALLET']
FastGas                     [ '140.00', '275.00', '535.00', '1050.00', '8400.00']          [ '6 PIECES', '12 PIECES', '24 PIECES', '48 PIECES', '1 PALLET']

I want to convert the price and variation columns to lists so I can explode them. My expected dataframe will look like this:

product_name                    price         variations
Cream Deluxe Gold (615g)        130.00       6 PIECES
Cream Deluxe Gold (615g)        255.00      12 PIECES 

I tried this code:

df = df.explode(['price','variations'])

and I'm getting my original dataframe and not my expected dataframe.

1 Answers

read_csv parses the list in the columns as a string by default. Hence you're not able to explode the columns. To read the columns as lists, you can define a custom converter that applies pd.eval:

import pandas as pd

df = pd.read_csv('filename.csv', converters={'price': pd.eval, 'variations': pd.eval})
Related