[英]How to generate a json file with a nested dictionary from pandas df?
我需要從 pandas dataframe 生成具有特定格式的 json 文件。 dataframe 看起來像這樣:
用戶身份 | product_id | 日期 |
---|---|---|
1 | 23 | 01-01-2022 |
1 | 24 | 05-01-2022 |
2 | 56 | 05-06-2022 |
3 | 23 | 02-07-2022 |
3 | 24 | 01-02-2022 |
3 | 56 | 02-01-2022 |
並且 json 文件需要具有以下格式:
{
"user_id": 1,
"items": [{
"product_id": 23,
"date": 01-01-2022
}, {
"product_id": 24,
"date": 05-01-2022
}]
}
{
"userid": 2,
"items": [{
"product_id": 56,
"date": 05-06-2022
}]
}
...etc
我嘗試了以下方法,但它不是正確的格式:
result = (now.groupby('user_id')['product_id','date'].apply(lambda x: dict(x.values)).to_json())
任何幫助將非常感激
out = (df[['product_id','date']].apply(dict, axis=1)
.groupby(df['user_id']).apply(list)
.to_frame('items').reset_index()
.to_dict('records'))
print(out)
[{'user_id': 1, 'items': [{'product_id': 23, 'date': '01-01-2022'}, {'product_id': 24, 'date': '05-01-2022'}]},
{'user_id': 2, 'items': [{'product_id': 56, 'date': '05-06-2022'}]},
{'user_id': 3, 'items': [{'product_id': 23, 'date': '02-07-2022'}, {'product_id': 24, 'date': '01-02-2022'}, {'product_id': 56, 'date': '02-01-2022'}]}]
下面的代碼可以解決這個問題。 它首先將日期時間轉換為日期列的字符串。 然后,它將 dataframe 轉換為所需的格式。
data是您保存為 excel 文件的數據表。
# Import libraries
import pandas as pd
import openpyxl
import json
# Read the excel data
data = pd.read_excel("data.xlsx", sheet_name=0)
# Change the data type of the date column (day-month-year)
data['date'] = data['date'].apply(lambda x: x.strftime('%d-%m-%Y'))
# Convert to desired json format
json_data = (data.groupby(['user_id'])
.apply(lambda x: x[['product_id','date']].to_dict('records'))
.reset_index()
.rename(columns={0:'items'})
.to_json(orient='records'))
# Pretty print the result
# https://stackoverflow.com/a/12944035/10905535
json_data = json.loads(json_data)
print(json.dumps(json_data, indent=4, sort_keys=False))
output:
[
{
"user_id": 1,
"items": [
{
"product_id": 23,
"date": "01-01-2022"
},
{
"product_id": 24,
"date": "05-01-2022"
}
]
},
{
"user_id": 2,
"items": [
{
"product_id": 56,
"date": "05-06-2022"
}
]
},
{
"user_id": 3,
"items": [
{
"product_id": 23,
"date": "02-07-2022"
},
{
"product_id": 24,
"date": "01-02-2022"
},
{
"product_id": 56,
"date": "02-01-2022"
}
]
}
]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.