python - 如何根据他们的行堆叠数据?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'}]
解决方案
我认为这可以满足您的所有需求:
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)
推荐阅读
- linux - powershell 相当于 bash/linux 中的组对象?
- vba - 如何从 excel vba 连接到 IBM Host on Demand 大型机终端
- python - Python:如何检查一个圆在所有 360 度上是否具有相等的半径
- php - 从乘法类继承访问静态变量(PHP)
- scala - 如何模拟由Scala对象中的函数初始化的val?
- javascript - 表上的双水平滚动 - JQuery
- firebase - 如何延迟 firebaseRecyclerAdapter.startListening(); ,那需要从onStart开始?
- java - Apache HttpResponse 获取未格式化的字符串而不是 XML
- makefile - Doxygen 使 pdflatex 在 Debian VM 上失败
- javascript - nodejs将流转换为json对象