So I have a list where each entry looks something like this:
JavaScript
x
2
1
"{'A': 1, 'B': 2, 'C': 3}"
2
I am trying to get a dataframe that looks like this
JavaScript
1
5
1
A B C
2
0 1 2 3
3
1 4 5 6
4
2 7 8 9
5
But I’m having trouble converting the format into something that can be read into a DataFrame. I know that pandas should automatically convert dicts into dataframes, but since my list elements are surrounded by quotes, it’s getting confused and giving me
JavaScript
1
4
1
0
2
0 {'A': 1, 'B': 2, 'C': 3}
3
4
I’ve tried using using json, concat’ing a list of dataframes, and so on, but to no avail.
Advertisement
Answer
eval
is not safe. Check this comparison
.
Instead use ast.literal_eval
:
Assuming this to be your list:
JavaScript
1
11
11
1
In [572]: l = ["{'A': 1, 'B': 2, 'C': 3}", "{'A': 4, 'B': 5, 'C': 6}"]
2
3
In [584]: import ast
4
In [587]: df = pd.DataFrame([ast.literal_eval(i) for i in l])
5
6
In [588]: df
7
Out[588]:
8
A B C
9
0 1 2 3
10
1 4 5 6
11