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

问题描述:

以下查询是抓取数据并创建CSV文件,我遇到的问题是名为'SPLE'的源将数据存储在数据库中,其编号为0,1 50.在CSV这些数字如何将数值数据更改为CSV文件中的文本

然而正在收集在CSV和创建CSV那些数来表示的话,例如当我想以某种方式,

0 =真

1 =假

50 =待定

有人可以告诉我这是怎么做的,我一直在努力呢? 我的代码:

从日期时间日期时间的进口从 进口elasticsearch Elasticsearch 导入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*"}}]}}},size=10) 


csv_file = 'File_' + str(datetime.now().strftime('%Y_%m_%d - %H.%M.%S')) + '.csv' 


header_names = { 'VT': 'Date', 'NCR': ‘ExTime', 'N': 'Name', 'DT': 'Party', ' RD ': 'Period'} 



with open(csv_file, 'w', newline='') 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) 




     w.writerow(my_dict) 

CSV文件的输出是:

Date  RD  Venue 
20171016 1  Central 
20171016 1  Central 
20171016 0  Central 
20171016 0  Central 
20171016 50  Central 
20171016 0  Central 
20171016 1  Central 
+0

[将数值数据更改为CSV文件中的文本]可能重复(https://*.com/questions/46784832/change-numerical-data-to-text-in-csv-file) –

看起来你让一个有点复杂,熊猫是你的朋友。

import pandas as pd 

def SPLE_fix(sple): 
    if sple == 0: 
     return('True') 
    elif sple == 1: 
     return('False') 
    else: 
     return('Pending') 


df=pd.read_csv('mycsvfile.csv') 

df['SPLE'] = df['SPLE'].apply(SPLE_fix) 

df.to_csv('newcsv.csv', index=False) 

输出newcsv.csv的:

Date,SPLE,Venue 
20171016,False,Central 
20171016,False,Central 
20171016,True,Central 
20171016,True,Central 
20171016,Pending,Central 
20171016,True,Central 
20171016,False,Central 

编辑:

对于*大熊猫的解决方案:

import csv 

def SPLE_fix(sple): 
    #just check for text in header 
    try: 
     sple[1]=int(sple[1]) 
    except: 
     return(sple) 

    #this part just changes the value 
    if sple[1] == 0: 
     sple[1] = 'True' 
    elif sple[1] == 1: 
     sple[1] = 'False' 
    else: 
     sple[1] = 'Pending' 

    return(sple) 


with open('mycsvfile.csv', 'r') as csvfile: 
    data=csv.reader(csvfile, delimiter=',') 
    new_data=[SPLE_fix(row) for row in data] 

with open('newcsv.csv', 'w', newline='') as csvfile: 
    cwrite=csv.writer(csvfile, delimiter=',') 
    cwrite.writerows(new_data) 

这应该得到同样的结果。可能不是最有效率的,但除非你这么做了很多次,否则不应该太重要。

+0

如果我可以不在我的电脑上安装熊猫,因为我在代理上? – Rich

+0

我已经添加了一个方法来获得相同的csv输出没有熊猫。 – SuperStew

+0

不幸的是,这是行不通的,我有一个函数来创建CSV并给它一个数据和时间的文件名。所以也许这是造成这个问题?让我更新我的帖子,以便你可以看到代码的一部分 – Rich