我获取了一个 json 数据集。数据集名称为 v2_OpenEnded_mscoco_train2014_questions.json 如何从数据集中拆分部分数据并将拆分数据保存到另一个 json 文件中?
这是我的数据集的示例:
{"image_id": 426004, "question": "How many buns are on the plate?", "question_id": 426004002}, {"image_id": 92846, "question": "What is the color of the vase without flowers?", "question_id": 92846000}, {"image_id": 92846, "question": "Is there anything red in this photo?", "question_id": 92846002}, {"image_id": 92846, "question": "What does that vase represent?", "question_id": 92846003}, {"image_id": 262166, "question": "What color is the couch?", "question_id": 262166002}, {"image_id": 262166, "question": "How many seats are available?", "question_id": 262166003}
我的数据集中大约有 443,757 条数据。我想将数据集拆分为 400 个不同的数据集,每个数据集都有 100 个数据。我如何使用 python 来自动化此操作? 如果可以用 pytorch 来完成这将是一个很大的帮助。
最佳答案
试试这个:
n_rows = 100
current_data = []
for i, e in enumerate(data):
if i % n_rows == 0 and i > 0:
with open(f'dataset_{i - n_rows}-{i}.json', 'w') as f:
json.dump(current_data, f)
current_data = []
current_data.append(e)
data
是一个包含您拥有的 json 的列表。我们对其进行迭代,并将每 n_rows
行写入一个新文件中。最后几行没有写。
关于python - 如何拆分json数据集并保存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66407955/