英文:
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)))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论