1

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?

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

8 Comments

@SPy - Can you add sample of this bad data? But obviously it is not easy :(
@SPy - I try some regex and failed. Maybe possible solution should be split, do you parse json file to lists ?
@SPy - OK, data are confidental?
@SPy - For me it working nice, like in this question - DF = pd.read_json(sourcePath, lines=True), for you it failed?
So solution from this not working? Also added your original code.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.