2

Although I referred many sources like How to convert string representation of list to a list? but I couldn't solve my problem below.

My list looked like below and I added this list to the dataframe as column, and saved the dataframe.

ls = [['abc'],['a"bcd"e', "ab'cde'"]]
df['list_col'] = ls
df.to_csv('path')

After, I opened the df dataframe, and I confirmed that the list changed to the string representation of list by the code below.

type(df.list_col[0]) # str

So I tried to make the string representation of my list to use the code below.

import ast
df.list_col = [ast.literal_eval(ls) for ls in df.list_col]
# SyntaxError: EOL while scanning string literal

Is there any solution I can solve this problem?

Trenton McKinney
  • 29,033
  • 18
  • 54
  • 66
shd04121
  • 23
  • 3

2 Answers2

2
  • Use the converters parameter of pandas.read_csv when reading the file in.
import pandas as pd
from ast import literal_eval

# test dataframe
ls = [['abc'],['a"bcd"e', "ab'cde'"]]
df = pd.DataFrame({'test': ls})

# save to csv
df.to_csv('test2.csv', index=False)

# read file in with converters
df2 = pd.read_csv('test2.csv', converters={'test': literal_eval})

print(type(df2.iloc[0, 0]))
[out]: list
Trenton McKinney
  • 29,033
  • 18
  • 54
  • 66
1

Is this what you want?

>>> ls = [['abc'],['a"bcd"e', "ab'cde'"]]
>>> l = [i for a in ls for i in a]
['abc','a"bcd"e', "ab'cde'"]
JenilDave
  • 560
  • 3
  • 13
  • Actually, what I intended was `[['abc'],['a"bcd"e', "ab'cde'"]]`, the original list, but thank you for your help! :) – shd04121 Jul 29 '20 at 08:54