我正在嘗試將 pandas 資料框轉換為嵌套的 json 并被卡住。資料框包含以下格式的資料:
description 69 70 project_id 60
1 Lorem Ipsum... 14 5679 CA
2 Lorem Ipsum... hom 15 2904 CA
3 Lorem Ipsum... im 14 5679 CA
我想要的是一個看起來像這樣的 JSON:
[ {
"issue": {
"project_id": 5679,
"description": "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.",
"custom_fields": [
{
"id": 69,
"value": null
},
{
"id": 60,
"value": "CA"
},
{
"id": 70,
"value": "14"
}
]
}
},
{
"issue": {
"project_id": 2904,
"description": "Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet ",
"custom_fields": [
{
"id": 69,
"value": "hom"
},
{
"id": 60,
"value": "CA"
},
{
"id": 70,
"value": "15"
}
]
}
},
這是我到目前為止所擁有的,但它不會產生所需的格式,例如我沒有得到的是 JSON 的標題(“問題”......)和嵌套(“id”:。 .., “價值”: ...)
j = (df_test.groupby(['description','project_id'])
.apply(lambda x: x[['69', '70', '84', '60']].to_dict('records'))
.reset_index()
.rename(columns={0:'custom_fields'})
.to_json(orient='records'))
關于我必須調整的任何想法?提前感謝任何幫助和提示
uj5u.com熱心網友回復:
我建議不要將它放在一個鏈式函式呼叫中,而是簡單地遍歷資料框并根據需要處理資訊:
import pandas as pd
import json
# create example data
df = pd.DataFrame({"description" : ['Lorem Ipsum', 'Lorem Ipsum', 'Lorem Ipsum'],
69: [None, "hom", "im"],
70: [14, 15, 14],
"project_id" : [5679, 2904, 5679],
60: ["CA", "CA", "CA"]
})
# convert data to desired format
res = []
custom_field_keys = [69, 60, 70]
for idx, row in df.iterrows():
entry = { key: value for key, value in row.items() if key not in custom_field_keys }
entry["custom_fields"] = [
{"id": key, "value": value} for key, value in row.items() if key in custom_field_keys
]
res.append({"issue": entry})
print(json.dumps(res, indent=2))
這產生:
[
{
"issue": {
"description": "Lorem Ipsum",
"project_id": 5679,
"custom_fields": [
{
"id": 69,
"value": null
},
{
"id": 70,
"value": 14
},
{
"id": 60,
"value": "CA"
}
]
}
},
{
"issue": {
"description": "Lorem Ipsum",
"project_id": 2904,
"custom_fields": [
{
"id": 69,
"value": "hom"
},
{
"id": 70,
"value": 15
},
{
"id": 60,
"value": "CA"
}
]
}
},
{
"issue": {
"description": "Lorem Ipsum",
"project_id": 5679,
"custom_fields": [
{
"id": 69,
"value": "im"
},
{
"id": 70,
"value": 14
},
{
"id": 60,
"value": "CA"
}
]
}
}
]
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/434042.html
