使用自定义列作为索引将Python转换为CSV

2024-05-16 08:20:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用下面的代码创建了一个Pandas数据帧并输出到JSON:

dataDict['grant_id'] = list(grant_ids)
dataDict['patent_title'] = list(patent_title)
dfjson = dfjson.transpose()
dfjson = pd.DataFrame.from_dict(dataDict, orient='index')
output_json =dfjson.to_json('output_json.json')

{"0":
{"grant_id":"US10357643",
"patent_title":"System for enhanced sealing of coupled medical flui,
 .... }}

但是,我不希望JSON中包含0。我希望它看起来像这样:

{"US10357643":{
"patent_title":"System for enhanced sealing of coupled medical flui,
 .... }}

我想使用grant_id作为索引,而不是0,1,2,3。。。有办法解决这个问题吗?你知道吗


Tags: idjsonforoutputtitlesystemlistenhanced
1条回答
网友
1楼 · 发布于 2024-05-16 08:20:04

我相信你需要^{}和双转置:

dfjson = pd.DataFrame({"0":{"grant_id":"US10357643",
                            "patent_title":"System1"},
    "1":{"grant_id":"US10357644",
                            "patent_title":"System2"}})
print (dfjson)
                       0           1
grant_id      US10357643  US10357644
patent_title     System1     System2

output_json = dfjson.T.set_index('grant_id').T.to_json()
print (output_json)
{"US10357643":{"patent_title":"System1"},"US10357644":{"patent_title":"System2"}}

dfjson.T.set_index('grant_id').T.to_json('output_json.json')

因此,似乎需要在转置之前创建索引:

dataDict['grant_id'] = list(grant_ids)
dataDict['patent_title'] = list(patent_title)

dfjson = pd.DataFrame.from_dict(dataDict, orient='index')
dfjson = dfjson.set_index('grant_id').transpose()

dfjson.to_json('output_json.json')

相关问题 更多 >