gpt4 book ai didi

使用自定义列作为索引的 Python Pandas 到 CSV

转载 作者:太空宇宙 更新时间:2023-11-04 04:04:52 25 4
gpt4 key购买 nike

我使用下面的代码创建了一个 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,
.... }}

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

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

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

最佳答案

我相信你需要DataFrame.set_index双转置:

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')

关于使用自定义列作为索引的 Python Pandas 到 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57552163/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com