我正在尝试在CSV的两列中使用“NCR”中的数据。但是,它们会相互覆盖,只会在“YesterdayTime”列中显示数据。
有没有一种方法可以在’ExTime’
和‘YesterdayTime’
两列中使用“NCR”中的数据?
我的密码
from datetime import datetime
from elasticsearch import Elasticsearch
import csv
es = Elasticsearch(["9200"])
res = es.search(index="search", body=
{
"_source": ["VT","NCR","N","DT","RD"],
"query": {
"bool": {
"must": [{"range": {"VT": {
"gte": "now/d",
"lte": "now+1d/d"}}},
{"wildcard": {"user": "mike*"}},
{"wildcard": {"user": "jane*"}},
{"wildcard": {"user": "kate*"}},
{"wildcard": {"user": "dave*"}},
{"wildcard": {"user": "rich*"}}
]}}},size=10)
csv_file = 'File_' + str(datetime.now().strftime('%Y_%m_%d - %H.%M.%S')) + '.csv'
header_names = { 'VT': 'Date', 'NCR': 'ExTime', 'NCR': 'YesterdayTime', 'N': 'Name', 'DT': 'Party', ' RD ': 'Period'}
with open(csv_file, 'w', newline='') as f:
w = csv.DictWriter(f, fieldnames=header_names.keys(), restval='', extrasaction='ignore')
w.writerow(header_names,)
for doc in res['hits']['hits']:
my_dict = doc['_source']
w.writerow(my_dict)
输出-
EX time
已替换为YesterdayTime
。DATE YesterdayTime Name Party Period
20170512 12/05/2017 15:39 1001 0 0
20170512 12/05/2017 15:39 1001 0 0
20170908 08/09/2017 02:42 1001 0 0
20170908 08/09/2017 06:30 1001 0 0
我想要的正确输出:
DATE YesterdayTime YesterdayTime Name Party Period
20170512 12/05/2017 15:39 12/05/2017 15:39 1001 0 0
20170512 12/05/2017 15:39 12/05/2017 15:39 1001 0 0
20170908 08/09/2017 02:42 08/09/2017 02:42 1001 0 0
20170908 08/09/2017 06:30 08/09/2017 06:30 1001 0 0
最佳答案
Python字典不支持重复键。您在header_names词典中最后一次出现的“NSC”将覆盖第一个。
关于python - 收集两列数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47266400/