sudheer naidu
sudheer naidu

Reputation: 162

How to preserve the datatype 'list' of a data frame while reading from csv or writing to csv

I want to preserve the datatype of a column of a data frame which is a list while writing it to csv file. when I read it, I have to have the values in lis format.

I have tried

pd.read_csv('namesss.csv',dtype = {'letters' = list})

but it says

 dtype <class 'list'> not understood

this is an example

df = pd.DataFrame({'name': ['jack','johnny','stokes'],
                  'letters':[['j','k'],['j','y'],['s','s']]})
print(type(df['letters'][0]))
df
<class 'list'>
name    letters
0   jack    [j, k]
1   johnny  [j, y]
2   stokes  [s, s]
df.to_csv('namesss.csv')
print(type(pd.read_csv('namesss.csv')['letters'][0]))
<class 'str'>

Upvotes: 1

Views: 843

Answers (1)

vlemaistre
vlemaistre

Reputation: 3331

You can use the ast module to make strings into lists :

import ast
df2 = pd.read_csv('namesss.csv')
df2['letters'] =[ast.literal_eval(x) for x in df2['letters'] ]

In [1] : print(type(df2['letters'][0]))
Out[1] : <class 'list'>

Upvotes: 1

Related Questions