The following series contains a string of dictionaries of key values. Split the list into columns a and column b in such a way that column a and column b will be 0 if the list is empty else, 1.
Input:
list = ["{'a': [], 'b': []}",
"{'a': [{'c':3,'d':56}], 'b': []}",
"{'a': [], 'b': [{'c':45,'d':67}]}",
"{'a': [{'c':48,'d':676}], 'b': [{'c':29,'d':90}]}" ]
df = pd.DataFrame(data=list,columns=['A'])
Output:
a | b |
---|---|
0 | 0 |
1 | 0 |
0 | 1 |
1 | 1 |
CodePudding user response:
Another version:
from ast import literal_eval
lst = [
"{'a': [], 'b': []}",
"{'a': [{'c':3,'d':56}], 'b': []}",
"{'a': [], 'b': [{'c':45,'d':67}]}",
"{'a': [{'c':48,'d':676}], 'b': [{'c':29,'d':90}]}",
]
df = pd.DataFrame(literal_eval(v) for v in lst)
df = df.applymap(bool).astype(int)
print(df)
Prints:
a b
0 0 0
1 1 0
2 0 1
3 1 1
CodePudding user response:
Similar solution like @Andrej Kesely answer - only removed converting to lists and double DataFrame.astype
:
df = pd.DataFrame(df.A.tolist()).astype(bool).astype(int)
print (df)
a b
0 0 0
1 1 0
2 0 1
3 1 1