Home > database >  How to get values from a column with format of dictionary?
How to get values from a column with format of dictionary?

Time:03-11

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?

CodePudding user response:

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()

CodePudding user response:

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
  • Related