下面的查询正在获取数据并创建一个CSV文件,我遇到的问题是名为“ SPLE”的源将数据存储在数据库中,其编号为0、1、50。
但是,在CSV中,这些数字正在CSV中收集,我想在创建CSV时以某种方式表示这些数字,例如
0 =真
1 =错误
50 =待定
有人可以告诉我如何做到这一点吗,我一直在努力吗?
我的代码:
from elasticsearch import Elasticsearch import csv es = Elasticsearch(["9200"]) res = es.search(index="search", body= { "_source": ["DTDT", "TRDT", "SPLE", "RPLE"], "query": { "bool": { "should": [ {"wildcard": {"CN": "TEST*"}} ] } } }, size=10) header_names = { 'DTDT': 'DATE', 'SPLE': 'TAG', ...} with open('mycsvfile.csv', 'w') as f: header_present = False for doc in res['hits']['hits']: my_dict = doc['_source'] if not header_present: w = csv.DictWriter(f, my_dict.keys()) w.writerow(header_names) header_present = True w.writerow(my_dict)
CSV文件中的输出为:
Date SPLE Venue 20171016 1 Central 20171016 1 Central 20171016 0 Central 20171016 0 Central 20171016 50 Central 20171016 0 Central 20171016 1 Central
仅供参考:
我尝试使用熊猫,但是我无法安装熊猫,所以我想知道是否还有其他方法可以解决?
您可以在将值写入csv之前更改其值:
mapping = {0: "True", 1: "False", 50: "Pending"} # Map `SPLE` sple = my_dict['SPLE'] my_dict['SPLE'] = mapping.get(int(sple), sple) # Map `NME` nme = my_dict['NME'] my_dict['NME'] = mapping.get(int(nme), nme) w.writerow(my_dict)