如何将字典列表转换为新数据框?

huangapple go评论59阅读模式
英文:

How to convert list of dictionaries to new dataframe?

问题

将数据集中已经存在的字典列表转换为数据框。数据集的结构如下所示。
记录的类型是字符串,所以我有困难首先将其转换为列表,我很困惑如何进行转换。数据位于一个CSV文件列中。

(https://i.stack.imgur.com/5H17D.png)
我尝试使用json_normalize(),但它没有起作用。
我想从该列创建新的数据框。
谢谢您的时间!

英文:

To convert list of dictionary already present in the dataset to a dataframe. The dataset looks something like this.
the records type are in string type, so i have challenges to convert to list first and i was confused how to convert it. the data was in a column csv files

(https://i.stack.imgur.com/5H17D.png)
i tried to use json_normalize() but it didn't work
i wanted to create new dataframe from that column
Thank you for your time!

答案1

得分: 1

首先使用 DataFrame.explode 按照 occupations 列,然后通过 literal_eval 将字符串转换为字典,最后在 json_normalize 中创建新的列并附加到其他列中:

import ast

out = df.explode('occupations').reset_index(drop=True)

out = out.join(pd.json_normalize(out.pop('occupations').apply(ast.literal_eval)))
英文:

First use DataFrame.explode by occupations column, then convert strings to dictionaries by literal_eval and last create new columns in json_normalize with append to another columns:

import ast

out = df.explode('occupations').reset_index(drop=True)

out = out.join(pd.json_normalize(out.pop('occupations').apply(ast.literal_eval)))

huangapple
  • 本文由 发表于 2023年7月13日 17:35:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76677942.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定