In Pandas is there a way to convert data to a list without using Eval?
I have the following df, I want to use dataframe operations against the list without first having to convert the list items to list using eval
#a b
#['4','2','6']
#['2','3','7']
#['1','2','8']
dff="""a
['4','2','6']
['2','3','7']
['1','2','8']"""
csvfile = io.StringIO("a b\n0 ['1','2','5'] ['2']\n1 ['2','3','4'] ['4']\n2 ['2','3','4'] []\n3 [] []\n")
df = pd.read_csv(csvfile, sep=' ')
As you can see the types are objects:
df.a[0]
# "['4','2','6']"
df.a.to_numpy()
# array(["['4','2','6']", "['2','3','7']", "['1','2','8']"], dtype=object)
How can i convert using pandas, these objects to lists rather than strings of lists?
I can iterate over the items and create the lists manually using eval:
eval(df.a[0])
['4', '2', '6']
But i'd like to have the dataframe have objects of lists, rather than strings of lists. Is that possible? To convert a string of lists to actual lists in the dataframe object?