将数值数据更改为CSV文件中的文本

时间:2017-10-17 07:34:44

标签: python python-3.x csv elasticsearch

以下查询是抓取数据并创建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

供参考:

我曾尝试使用pandas但是我无法安装pandas所以我想知道是否还有另外一种解决方法?

2 个答案:

答案 0 :(得分:1)

您可以在将值写入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)

答案 1 :(得分:0)

如果没有看到my_dict的内容,这只是一个最好的猜测,但我会尝试并协助陈述我的假设。

对于my_dict,如下所示:

my_dict = {"DATE": ..., "SPLE": ..., ...}

w.writerow(my_dict)之前,您可以将SPLE条目解析为您想要的内容:

my_dict["SPLE"] = str(bool(int(my_dict["SPLE"]))) if int(my_dict["SPLE"]) in [0,1] else "Pending"

这是一种紧凑形式:

# Check to see if current "SPLE" value can be described 
# as True (1) or False (0)
if int(my_dict["SPLE"]) in [0,1]:
    # Yes it can, so change it to True or False string by type conversion
    my_dict["SPLE"] = str(bool(int(my_dict["SPLE"])))
else:
    # Entry is not a 0 or 1 so not described by true or false
    # assign to "Pending"
    my_dict["SPLE"] = "Pending"