gpt4 book ai didi

Python 在写入 CSV 文件之前检查列数据是否存在

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

你好有字典数据,如图所示:

{'Count': 5, '_id': {'ele_id': ['17cd-4a9f-9671-80eda11f9c53'], 'day': '2015-09-22'}, 'name': 'Default Astn'}
{'Count': 2, '_id': {'ele_id': ['17cd-4a9f-9671-80eda11f9c53'], 'day': '2015-09-18'}, 'name': 'Default Astn'}
{'Count': 1, '_id': {'ele_id': ['ccdf-4e0b-a87c-4e7738a0ed33'], 'day': '2015-09-14'}, 'name': 'sharepoint Astn'}
{'Count': 1, '_id': {'ele_id': ['2b9f-436b-a2ff-c4bc4059a9c8'], 'day': '2015-09-14'}, 'name': 'JPL Astn'}
{'Count': 2, '_id': {'ele_id': ['17cd-4a9f-9671-80eda11f9c53'], 'day': '2015-09-14'}, 'name': 'Default Astn'}

想要写入包含如下列和数据的 CSV:

Date        Name           Count
2015-09-22 Default Astn 5
2015-09-18 Default Astn 2
2015-09-14 sharepoint Astn 1
JPL Astn 1
Default Astn 2

我面临的问题是第 3 行,如果第 1 列已经相同,只需添加第 2 和第 3 列。我的代码如下

with open('test.csv', 'wb') as f:
fieldnames = ['Date','Name','Count']
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
for line in data:
writer.writerow({'Date' : line['_id']['day'],'Name' : line['name'], 'Count':line['Count']})

最佳答案

试试这个......还没有测试,但我认为逻辑保持不变......

with open('test.csv', 'wb') as f:
fieldnames = ['Date','Name','Count']
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
prev_date = ''
for line in data:
curr_date = line['_id']['day']
if curr_date == prev_date:
writer.writerow({'Date' : '','Name' : line['name'], 'Count':line['Count']})
else:
writer.writerow({'Date' : curr_date,'Name' : line['name'], 'Count':line['Count']})
prev_date = curr_date

关于Python 在写入 CSV 文件之前检查列数据是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32844179/

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