Skip to main content
 首页 » 编程设计

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

2024年11月01日16findumars

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