0

if the 6th element of each row of my file is 2, I want to add 4 to element 10 on the same line. I'm running into problems with addition.

import csv

plusfour=[]
with open("101.txt", 'rb') as f:
    reader = csv.reader(f)
    # make it into a list
    data = list(reader)
    # for each line in data
    dataline = 0
    for i in data:
    if data[dataline][5] is "2":
        plusfour.append(int(data[dataline][9])+4)
        print(plusfour)
        #print(data[dataline][9])
    dataline +=1

but it won't print anything. I also tried

        if data[dataline][5] is "2":
            print(data[dataline][9])

and that works, so the issue is with how I'm trying to add 4 to that value. I can't figure out what I'm doing wrong above in specifying data[dataline][9] as an integer that can be added to.

Basically, if the value of one column in my csv is 2, how can I add 4 to the value of another column on the same row? I need to iterate through each row.

here's part of the file I'm loading: input file

here's the output of my 2nd code snippet: output of my 2nd code snippet

EDIT: I was having problems because some of my values were blank. I now have this:

import csv

plusfour=[]
# open file with all subjects in it 
with open("101.txt", 'rb') as f:
    reader = csv.reader(f)
    # make it into a list
    data = list(reader)
    # for each line in data
    dataline = 0
    valid_responses = ("1", "2")
for i in data:
    if data[dataline][5] not in valid_responses:
        plusfour.append("NA")
    elif int(float(data[dataline][5])) == 2:
        # add 4 to value of 10th element in same row 
        data[dataline][9] = int (float(data[dataline][9]))+4
        plusfour.append(data[dataline][9])
        print(plusfour)
    elif int(float(data[dataline][5])) == 1:
        plusfour.append(data[dataline][9])
    dataline +=1

and am getting this error: data[dataline][9] = int (float(data[dataline][9]))+4 ValueError: could not convert string to float:

Maria
  • 1,247
  • 1
  • 13
  • 21
  • 1
    Not sure I understand your question. Your code doesn't use `print` or otherwise produce output, so of course it won't print anything. If you want to print the value with 4 added, you need to. . . print it. – BrenBarn Mar 17 '15 at 18:09
  • sorry, I forgot to include the print call. I printed plusfour. and got this error: " plusfour.append(int(data[dataline][9])+4) ValueError: invalid literal for int() with base 10:'' I'll add that now. – Maria Mar 17 '15 at 18:12
  • @Maria: Can you shear sample input file and respective output with us or me(vivekbsable@gmail.com)?? – Vivek Sable Mar 17 '15 at 18:12
  • "Basically, if the value of one column in my csv is 2, how can I add 4 to the value of another column on the same row?" The question is somewhat unclear. Why is the value (2) of column X relevant? – Tom Dalton Mar 17 '15 at 18:12
  • Could it be that you try to compare an integer to a string? – Anselm Scholz Mar 17 '15 at 18:12
  • 1
    The code you posted is not your real code, since it's missing a parenthesis on the `open` call. Please post actual code that demonstrates the problem. – BrenBarn Mar 17 '15 at 18:14
  • @VivekSable I edited my post- is that what you wanted? – Maria Mar 17 '15 at 18:21
  • @TomDalton it's complicated. numbers in column 6 range from 1-4. I have 2 sessions of 8 blocks. if column 10 = 2, it means the data refers to session 2, which is really blocks 5-8. – Maria Mar 17 '15 at 18:24
  • @AnselmScholz possibly... but I'm not comparing a string to anything as far as I can tell. as I understand it, if data[dataline][5] is "2" selects lines where data[dataline][5] is 2, but I'm not trying to use the "2" to do any math. I could be wrong though – Maria Mar 17 '15 at 18:26
  • @BrenBarn sorry. fixed now! – Maria Mar 17 '15 at 18:26

3 Answers3

1

Problem:

Create New Column in Input file according rules, Following are some rules

  1. If the 5th value is empty or not digit, you can just put "NA" or something in the new variable.
  2. If the 5th is 2 and 9th is empty or not digit, you can just put "NA" in the new variable
  3. If the 5th is 2 and 9th is integer, you can just add 4 in it.

Algo:

  1. Open Input file for read and open output file write mode.
  2. Iterate every row from the input file i.e. for row in reader:
  3. Get 5th item from the each row. Did Type Casting with Exception Handling.
  4. If step 3 raise ValueError exception then add new column value as NA then write to output file and continue i.e. iterate next row.
  5. If 5th item value is equal to 2 then get value of 9th item from th row.
  6. Did Type casting with exception handling to get 9th item.
  7. If step 6 raise ValueError exception then add new column value as NA then write to output file and continue i.e. iterate next row.
  8. Otherwise add 4 into value of 9th item and write into output file.
  9. We can do same to other target values.

code:

with open("101.txt", 'rb') as fp1:
    reader = csv.reader(fp1)
    #- open output file
    with open('101_output.csv', 'wb') as fp2:
        writer = csv.writer(fp2, delimiter=',')


    #- Iterate on input files
    for row in reader:
        try:
            item_5 = int(row[5])
        except ValueError:
            #- Create copy of row
            new_row = list(row)
            #- Append 9th value
            new_row.append("NA")
            #- Write row
            writer.writerow(new_row)
            print "Error1: Type Casting value %s"%row[5]
            continue

        new_row = list(row)
        if item_5 == 2:
            # add 4 to value of 10th element in same row 
            try:
                item_13 = int(row[9])+4
                new_row.append(item_13)
            except ValueError:
                new_row.append("NA")
        elif item_5 == 1:
            # keep data[dataline][9] the same
            try:
                item_13= int (row[9])+0
                new_row.append(item_13)
            except ValueError:
                new_row.append("NA")
        else:
            #- add same value of 9th item to 13th item
            new_row.append(row[9])
        writer.writerow(new_row)
Vivek Sable
  • 9,938
  • 3
  • 40
  • 56
0

try

import csv

plusfour=[]
with open("101.txt", 'rb' as f:
    reader = csv.reader(f)
    # make into a list
    data = list(reader)
    # counter
    dataline = 0
    for i in data:
        if int(float(data[dataline][5])) == 2:
            # add 4 to value of 10th element in same row 
            data[dataline][9] = int (float(data[dataline][9]))+4
            plusfour.append(data[dataline][9])
            print(plusfour)
        dataline +=1
Ting
  • 23
  • 7
0

One thing to note is that you're mixing up equality with identity:

This line:

if data[dataline][5] is "2":

Compares the content of dataline[5] with another str ("2") to check if they are the same object (identity). This will probably fail, and what oyu actually want is to check if they're equal (that is, composed of the same characters in the same order), so use == (equality):

if data[dataline][5] == "2":

Also, make sure you're comparing the same types "2" (str) is not equal to 2 (int).

To make sure, convert to the more general type:

 x = 2
 y = "2"
 x == y # False
 str(x) == str(y) # True
Community
  • 1
  • 1
Reut Sharabani
  • 30,449
  • 6
  • 70
  • 88