'How to get values from a column with format of dictionary?
If I have adata frame with this column and this information
slice_info time
----------------------------------------- -----
{'gaming': 2, 'main': 92, 'working': 9} 2021-09-11 00:04:00
{'gaming': 4, 'main': 78, 'working': 10} 2021-09-11 00:04:00
.....
How can I get the values that belong to gaming and the sum this 2 and 4 value?
Solution 1:[1]
You could just .apply
a function to retrieve the value from the dictionary and then sum those values:
df["slice_info"].apply(lambda entry: entry["gaming"]).sum()
Solution 2:[2]
Parse and convert:
import json
rows = []
for line in data.splitlines()[2:]:
rows.append(json.loads(line.split('}')[0].replace("'", '"') + "}"))
print(rows[0]["gaming"]) # 2
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | aaossa |
Solution 2 | MartinKondor |