python - 收集两列数据

标签 python python-3.x csv elasticsearch python-3.6

我正在尝试在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/

相关文章:

python - 如何在 Python 3 中导入上层包

python - CSV 中多行的字符串替换

c# - 从 CSV 文件中读取数据

python - 重置 pandas 数据框的值

python - Pandas 中的多键横截面。处理未命中和重复索引

python - 高效地将值从一列替换为另一列 Pandas DataFrame

python - 通过代理使用 urllib2

python - LabelEncoder() 对于相同的输入返回不同的值?

python - 为包含单词的列表生成唯一的 ID

python - 使用 python 从 Azure 机器学习服务中删除并列出所有模型和部署服务