-1

我有一个文件,我正在尝试使用 Python 中的数据填充第二个文件。在填充时,我正在应用一些if语句来操作第二个文件中的一列。

我想使用这些if语句执行的操作:检查文件中的第 31 列,如果它的值是第 32 列中的0返回0值,如果它的值为空白,则2在第 32 列中返回值,并且对于所有其他非零和非空白值返回1第 32 列中的值。

with open('DE_Combined_' + time.strftime("%Y-%m-%d")+".csv", "rb") as in_file, open('DE_Combined_PD_' + time.strftime("%Y-%m-%d")+".csv", "wb") as out_file:
   reader = csv.reader(in_file)
   writer = csv.writer(out_file)
   headers = next(reader, None)  # returns the headers or `None` if the input is empty
   if headers:
        writer.writerow(headers)
   for row in reader:
       if row[30] != 0:
           row[31] = 1
       else:
           row[31] = 0
       if row[30] == "":
           row[31] = 2
       writer.writerow(row)

这似乎是一个非常简单的问题,但我的输出文件给了我错误的结果。它1在第 32 列中的0值对应于第 31 列中的值。它应该0在两列中。尽管2值与blank第 31 列中的值相反。

请帮助我解决这个问题,因为在多次尝试发现if我使用的语句逻辑有问题之后,我现在一无所知。

实际 O/P 的片段:(两行中的最后 2 个条目是相关的列)

05/23/2013  May 2013    2013    4   2   Thursday    UK  O2  £   NOKIA   100 NOKIA 100   Smartphone  Symbian NA          9.99            N       Pay & Go    Pay & Go                    0.64222 0   1
05/23/2013  May 2013    2013    4   2   Thursday    UK  O2  £   NOKIA   100 NOKIA 100   Smartphone  Symbian NA  Pink        9.99            N       Pay & Go    Pay & Go                    0.64222 0   1

I/P Snippet:(前 2 行)(最后 2 列是相关列)

Date,Month,Fiscal_Year,Calendar_Year,FY_Quarter,CY_Quarter,Day_of_Week,Geography,MO,Currency,Device_OEM,Device_Name,GDN,Device_Type,Device_OS,Device_Franchise,Device_Color,Device_Storage_in_GB,Device_Price,Device_Monthly_Price,Additional,Device_Refurb,Plan_COMPARISON,Plan_Name,Plan_Contract_Length,Plan_Monthly_Price,Plan_Data_in_GB,Plan_Minutes,Plan_Texts,Exchange_Rate_vs_1USD,Difference,Difference_Flag
05/23/2013,May,2013,2013,4,2,Thursday,UK,O2,£,NOKIA,100,NOKIA 100,Smartphone,Symbian,NA,,,9.99,,,N,,Pay & Go,Pay & Go,,,,,0.64222,0.0,
05/23/2013,May,2013,2013,4,2,Thursday,UK,O2,£,NOKIA,100,NOKIA 100,Smartphone,Symbian,NA,Pink,,9.99,,,N,,Pay & Go,Pay & Go,,,,,0.64222,0.0,
4

4 回答 4

3

文档

从 csv 文件读取的每一行都作为字符串列表返回。不执行自动数据类型转换。

也许你if row[30] != 0应该改为if row[30] != "0"

于 2013-05-23T12:32:32.450 回答
1

将您的任务分成读取、操作和写入数据的函数。

要将表格读入列表:

def importCSV(fname):
    """ Returns a tuple using a CSV as input. First tuple is the
    header. 
    Second tuple is a dictionary with all the data.
    """
    data = []
    with open(fname, 'rb') as csvfile:
        reader = csv.DictReader(csvfile, delimiter=',')
        header = reader.fieldnames
        for lines in reader:
            data.append(lines)
        return (header, data)

header, data = importCSV('myfile.csv')

现在操纵您的数据:

for line in data:
    do something to line...
....

然后写你的数据:

def CreateCSVFromList(header, source, outputfile):
    """Creates a CSV from a 2D List.
    Header should be a simple list for each column in the resulting list.
    Source is the list.
    Output file is what is written. Include the .csv extension please.
    No error-checking is being done at the moment.
    """
    import csv
    with open(outputfile, 'wb') as csvfile:
        writer = csv.writer(csvfile, dialect='excel')
        writer.writerow(header)
        for row in source:
            writer.writerow(row)


CreateCSVFromList(header, data, 'output.csv')
于 2013-05-23T13:21:20.750 回答
1

如果我将您的逻辑更改为此(请记住,除非您使用 等转换它们,否则一切都是int()字符串float()

for row in reader:
    print "'%s'" % row[30]
    if float(row[30]) != 0:
        row[31] = '1'
    else:
        row[31] = '0'
    if row[30] == "":
        row[31] = 2
    writer.writerow(row)

我得到这个输出:

05/23/2013,May,2013,2013,4,2,Thursday,UK,O2,£,NOKIA,100,NOKIA 100,Smartphone,Symbian,NA,,,9.99,,,N,,Pay & Go,Pay & Go,,,,,0.64222,0.0,0
05/23/2013,May,2013,2013,4,2,Thursday,UK,O2,£,NOKIA,100,NOKIA 100,Smartphone,Symbian,NA,Pink,,9.99,,,N,,Pay & Go,Pay & Go,,,,,0.64222,0.0,0

最后一个元素为0;这就是问题所在,对吧?

于 2013-05-23T13:51:26.613 回答
0

试试这个:

_buffer = ''
for row in reader:
    if reader.line_num == 31:
        if row == ['']:             #check whether 31st row is empty
            _buffer = 2               #if that's true write `2`to line 32

        elif row == ['0']:      #if that's false check wheter 31st row = 0
            _buffer = 1           #if true, write `1`to line 32

        else:                 
            _buffer = 1 

    if reader.line_num == 32:
        row = _buffer

    writer.writerow(row)
于 2013-05-23T12:37:28.373 回答