我有一个 csv 数据:
<块引用>dataf = pd.DataFrame{'title':['tit1', 'tit1', 'tit2' 'tit2','tit3'], 'context':['con1', 'con1', 'con2', 'con2', 'con3'], '答案':['text1', 'text2', 'text3', 'text4', 'text5'], '问题':['que1', 'que2', 'que3', 'que4', 'que5'], 'id':['DDA', 'SAV'、'AFS'、'ML'、'MLI']}
我想使用 python 将其转换为嵌套的 json 格式,如下所示
[
{
"title": "tit1",
"paragraph": [
{
"context": "con1",
"qas": [
{
"answers": "text1",
"question": "que1",
"id": "DDA"
},
{
"answers": "text2",
"question": "que2",
"id": "SAV"
}
]
}
]
},
{
"title": "tit2",
"paragraph": [
{
"context": "con2",
"qas": [
{
"answers": "text3",
"question": "que3",
"id": "AFS"
},
{
"answers": "text4",
"question": "que4",
"id": "ML"
}
],
"context": "con3",
"qas": [
{
"answers": "text5",
"question": "que5",
"id": "MLI"
}
]
}
]
},
]
它继续用于其他各种数据
答案 0 :(得分:0)
这对你有用吗?
df = []
cont = 0;
for index, row in dataf.iterrows():
if cont == 0:
cont +=1
continue
dict = {}
list = []
item = {}
qas = {}
qas['answers'] = row[2]
qas['question'] = row[3]
qas['id'] = row[4]
item['context'] = row[1]
item['qas'] = []
item['qas'].append(qas)
dict[dataf[0][0]] = row[0]
dict['paragraph'] = []
dict['paragraph'].append(item)
#print(dict)
df.append(dict)
print(df)
输出:
[{'title': 'tit1', 'paragraph': [{'context': 'con1', 'qas': [{'answers': 'text1', 'question': 'que1', 'id': 'DDA'}]}]}, {'title': 'tit1', 'paragraph': [{'context': 'con1', 'qas': [{'answers': 'text2', 'question': 'que2', 'id': 'SAV'}]}]}, {'title': 'tit2', 'paragraph': [{'context': 'con2', 'qas': [{'answers': 'text3', 'question': 'que3', 'id': 'AFS'}]}]}, {'title': 'tit2', 'paragraph': [{'context': 'con2', 'qas': [{'answers': 'text4', 'question': 'que4', 'id': 'ML'}]}]}]