Reputation: 625
I Have Dataframe as below,
text num w wei
0 he is good 0 [a, b] [1, 2]
1 hello 1 [c, b] [3, 2]
2 here 4 [a, c] [1, 3]
I want to get like this,
text num w wei dic_w_wei
0 he is good 0 [a, b] [1, 2] {"a": 1, "b":2}
1 hello 1 [c, b] [3, 2] {"c": 3, "b":2}
2 here 4 [a, c] [1, 3] {"a": 1, "c":3}
dic_w_wei is new column from above w, and wei. how to get this new columns.
now at end i want dictionary like this from this dataframe,
{"a": 2, "b": 4, "c": 6}
where , i am summing it all value of a, b and c.
Upvotes: 0
Views: 594
Reputation: 75120
Try with apply
;
df['dic_w_wei'] = df[['w','wei']].apply(lambda x: dict(zip(*x)),axis=1)
print(df)
text num w wei dic_w_wei
0 he is good 0 [a, b] [1, 2] {'a': 1, 'b': 2}
1 hello 1 [c, b] [3, 2] {'c': 3, 'b': 2}
2 here 4 [a, c] [1, 3] {'a': 1, 'c': 3}
Once we have this column you can do:
pd.DataFrame(df['dic_w_wei'].tolist()).sum().astype(int).to_dict()
{'a': 2, 'b': 4, 'c': 6}
Example df below:
df = pd.DataFrame({'text': {0: 'he is good', 1: 'hello', 2: 'here'},
'num': {0: 0, 1: 1, 2: 4},
'w': {0: ['a', 'b'], 1: ['c', 'b'], 2: ['a', 'c']},
'wei': {0: [1, 2], 1: [3, 2], 2: [1, 3]}})
Upvotes: 2