question.it
question.it

Reputation: 2968

Convert List Like String to Python Dataframe

I have string variable which contains list like values

How To convert string values to dataframe?

string = '[[2017, 1050], [2016, 1069], [2015, 1173]]'
pd.DataFrame([item for item in string])

# Giving wrong results

Need result like below

      0     1
0  2017  1050
1  2016  1069
2  2015  1173

Also, second column contains special characters like (s) -- NA w * - etc

ast.literal_eval raises an exception if the input isn't a valid datatype. How to overcome this?

Upvotes: 1

Views: 57

Answers (1)

jezrael
jezrael

Reputation: 862611

Use ast, list comprehension is not necessary:

import ast

string = '[[2017, 1050], [2016, 1069], [2015, 1173]]'

df = pd.DataFrame(ast.literal_eval(string))
print (df)
      0     1
0  2017  1050
1  2016  1069
2  2015  1173

Upvotes: 1

Related Questions