将数字数据更改为CSV文件中的文本 [英] Change numerical data to text in CSV file

查看:373
本文介绍了将数字数据更改为CSV文件中的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下查询正在获取数据并创建CSV文件,我遇到的问题是名为 SPLE的源将数据存储在数据库中,其编号为0、1、50。

The below query is grabbing data and creating a CSV file, the issue that I am having is that the source called ‘SPLE’ stores data in the database with numbers of 0, 1, 50.

但是在CSV中这些数字是在CSV中收集的,我想以某种方式在创建CSV时将那些数字表示为单词,例如,

However in the CSV those numbers are being collected in the CSV and I would like somehow when creating the CSV those number to represent words such as,

0 =正确

1 =错误

50 =待处理

请问有人告诉我这是怎么做的,我一直在努力吗?

Could someone show me how this is done please, I have been struggling on this?

我的代码:

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文件中的输出为:

The output in the CSV file is:

Date       SPLE     Venue
20171016    1       Central
20171016    1       Central
20171016    0       Central
20171016    0       Central
20171016    50      Central
20171016    0       Central
20171016    1       Central

仅供参考:

我尝试使用熊猫,但无法安装熊猫,所以我想知道是否有

I have tried to use pandas however I am unable to install pandas so I am wondering if there is another way around this?

推荐答案

您可以先更改值,然后再将其写入csv:

You can change the value before you write it to the 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)

这篇关于将数字数据更改为CSV文件中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆