user3700386
user3700386

Reputation: 89

Finding same values in a row of csv in python

I have a code that looks for numbers within a csv file that are within 1.0 decimal places of each other in the same row. Although, when I run it, it prints everything. Not just rows that have the condition that I want i.e. that the values from the 2nd and 3rd column be within 1.0 of each other. I want to run the code and have it display, the first column (the time at which it was recorded or better yet the column number), the 2nd and the 3rd column because they should be within 1.0 of each other. This is what the data file looks like:

Time    Chan1       Chan2
04:07.0 52.31515503 16.49450684
04:07.1 23.55230713 62.48802185
04:08.0 46.06217957 24.94955444
04:08.0 41.72077942 31.32516479
04:08.0 19.80723572 25.73182678

Here's my code:

import numpy as np
from matplotlib import *
from pylab import *

filename = raw_input("Enter file name: ") + '.csv'
filepath = '/home/david/Desktop/' + filename


data = np.genfromtxt(filepath, delimiter=',', dtype=float)



first=[row[0] for row in data]
rownum1=[row[1] for row in data]
rownum2=[row[2] for row in data]



for row in data:
    if ((abs(row[1]-row[2]) <= 1.0)):
        print("The values in row 0 are 1 and 2, are within 1.0 of each other.", first, rownum1, rownum2)

This is my output:

26.3460998535, 44.587371826199998, 42.610519409200002, 24.7272491455, 89.397918701199998, 25.479614257800002, 30.991180419900001, 25.676086425800001

But I want this as an output:

4:09.0, 23.456, 22.5

Upvotes: 0

Views: 148

Answers (1)

Jihun
Jihun

Reputation: 1485

You can do that like this:

data = np.genfromtxt(filepath, names=True, dtype=None)
idx = np.abs(data['Chan1'] - data['Chan2'])<1
print data[idx]

Upvotes: 1

Related Questions