Convert string representation of list to list in dataframe column

Viewed 346

I have cvs file like this:

number    file
  1       [file1,file2]
  2       [file1]
  3       [file3,file4]

with datatype of column file is list. But when I read that file again, I got datatype of column file is str. The output is like this:

>>> df = pd.read_csv('file.csv')
>>> for col in df:
>>>    print (df[col].apply(type))
<class 'int'>
<class 'int'>
<class 'int'>
<class 'str'>
<class 'str'>
....

But, I want to read that value as a list. I've tried this [https://stackoverflow.com/a/1894296/10907221]. But I can't apply it to dataframe. Can someone help me to solve this problem?

Thank you

1 Answers

If you really want to have more than one file per number you should transform your input to:

number    file
  1       file1
  1       file2
  2       file1
  3       file3
  3       file4

Then to select them as a list you can do:

df[df["number"] == 1]

Or any number you want.

Related