【问题标题】:How to change numerical data to text in CSV file如何将数值数据更改为 CSV 文件中的文本
【发布时间】:2017-10-17 17:08:28
【问题描述】:

下面的查询是抓取数据并创建一个 CSV 文件,我遇到的问题是名为“SPLE”的源在数据库中存储了数字为 0、1、50 的数据。

但是在 CSV 中,这些数字正在被收集到 CSV 中,我希望在创建 CSV 时以某种方式将这些数字表示为诸如,

0 = 真

1 = 错误

50 = 待处理

有人可以告诉我这是怎么做到的吗,我一直在努力解决这个问题? 我的代码:

从日期时间导入日期时间 从弹性搜索导入弹性搜索 导入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

【问题讨论】:

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


【解决方案1】:

看起来你让它有点复杂,pandas 是你的朋友。

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)

这应该得到相同的结果。可能不是最有效的,但除非你这样做很多次,否则它应该没有太大关系。

【讨论】:

  • 如果因为我在代理上而无法在我的计算机上安装 pandas 怎么办?
  • 我添加了一种方法,无需熊猫即可获得相同的 csv 输出。
  • 不幸的是,这不起作用,我有一个函数可以创建 CSV 并为其提供数据和时间的文件名。所以也许这导致了这个问题?让我更新一下我的帖子,这样你就可以看到那部分代码
  • 您能否提供一些有关您遇到的错误的信息?
  • 没有错误,CSV中的数字没有转换成文本。我已经更新了上面的代码,以便您查看更新的版本。谢谢
猜你喜欢
  • 2018-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多