首页 > 解决方案 > 如何根据他们的行堆叠数据?Python

问题描述

我有一个大数据集,比如~30000 条记录。我想提取像“动画”、“喜剧”、“家庭”这样的词。我将单词提取出来并删除是成功的id,但是我不知道如何根据它们的行将单词堆叠回去。

我的代码目前:

import ast, json
import pandas as pd
from csv import reader
file_name = 'xx.csv'
data = []
with open(file_name, 'r', encoding= 'unicode_escape') as read_obj:
    csv_reader = reader(read_obj)
    headings = next(csv_reader)

    for i in csv_reader:
        data.extend(ast.literal_eval(i[7]))
     
df = pd.DataFrame(data)
del df["id"]
print(df)

它会产生结果:

            name
0      Animation
1         Comedy
2         Family
3      Adventure
4        Fantasy
         ...
40060      Drama
40061   Thriller
40062     Action
40063      Drama
40064   Thriller

大数据集为csv格式,但单元格应为json格式。

样本数据:

[{'id': 16, 'name': 'Animation'}, {'id': 35, 'name': 'Comedy'}, {'id': 10751, 'name': 'Family'}]
[{'id': 12, 'name': 'Adventure'}, {'id': 14, 'name': 'Fantasy'}, {'id': 10751, 'name': 'Family'}]
[{'id': 10749, 'name': 'Romance'}, {'id': 35, 'name': 'Comedy'}]
[{'id': 35, 'name': 'Comedy'}, {'id': 18, 'name': 'Drama'}, {'id': 10749, 'name': 'Romance'}]
[{'id': 35, 'name': 'Comedy'}]
[{'id': 28, 'name': 'Action'}, {'id': 80, 'name': 'Crime'}, {'id': 18, 'name': 'Drama'}, {'id': 53, 'name': 'Thriller'}]
[{'id': 28, 'name': 'Action'}, {'id': 80, 'name': 'Crime'}, {'id': 18, 'name': 'Drama'}, {'id': 53, 'name': 'Thriller'}]
[{'id': 28, 'name': 'Action'}, {'id': 80, 'name': 'Crime'}, {'id': 18, 'name': 'Drama'}, {'id': 53, 'name': 'Thriller'}]
[{'id': 35, 'name': 'Comedy'}, {'id': 10749, 'name': 'Romance'}]
[{'id': 28, 'name': 'Action'}, {'id': 12, 'name': 'Adventure'}, {'id': 18, 'name': 'Drama'}, {'id': 10751, 'name': 'Family'}]

标签: pythonjsonpandascsv

解决方案


我认为这可以满足您的所有需求:

import json
import pandas as pd

df = pd.read_csv(file_name, encoding='unicode_escape', usecols=['name'])

result = df.to_json(orient='records')
parsed = json.loads(result)
json.dumps(parsed, indent=4)

推荐阅读