Skip to content
Advertisement

CSV data to Python dictionary

I wrote my data which was in lists and dicts to a csv file, and when i import the csv file using pd.read_csv('file.csv'), everything becomes strings. How can i keep or convert it to its original format?

Originally, everything was in a dataframe and then written to a CSV file using df.to_csv(r'./file.csv').

csv_data['ln2']
Out[36]: 
0        {0: [67, 1], 1: [67, 1], 2: [67, 1], 3: [67, 1...
1        {0: [67, 1], 1: [67, 1], 2: [67, 1], 3: [67, 1...
2        {0: [67, 1], 1: [67, 1], 2: [67, 1], 3: [67, 1...
3        {0: [67, 1], 1: [67, 1], 2: [67, 1], 3: [67, 1...
4        {0: [67, 1], 1: [67, 1], 2: [67, 1], 3: [67, 1...
                               ...                        
43244    {0: [71, 1], 1: [73, 1], 2: [79, 1], 3: [80, 1...
43245    {0: [71, 1], 1: [73, 1], 2: [79, 1], 3: [80, 1...
43246    {0: [71, 1], 1: [73, 1], 2: [79, 1], 3: [80, 1...
43247    {0: [71, 1], 1: [73, 1], 2: [79, 1], 3: [80, 1...
43248    {0: [71, 1], 1: [73, 1], 2: [79, 1], 3: [80, 1...
Name: ln2, Length: 43249, dtype: object

all the rows are strings.

Advertisement

Answer

This will read the column as dicts:

df = pd.read_csv('file.csv', converters={'ln2': eval})
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement