Search code examples
python-2.7csvcanopy

reading in certain rows from a csv file using python


Say I have a csv file that looks like the following with the first column containing frequencies and the second column containing the power level (dBm).

Frequency | dBm

1           -11.43
2.3         -51.32
2.5         -12.11
2.8         -11.21
3.1         -73.22
3.2         -21.13

I only want to read in the data sets of this file that have a (dBm) value between -13 and -10. Therefore, in this example I only want the data sets (1, -11.43)(2.5, -12.11)(2.8, -11.21) to be read into my program variables x1 and y1. Could someone give me some help in how I could do this?


Solution

  • You can just use the csv library and check if each meets your criteria.

    Something like this should work on your file:

    with open('file.csv') as csvfile:
            reader = csv.reader(csvfile,delimiter=' ')
            reader.next()
            reader.next()
            for row in reader:
                    a = [float(i) for i in row if i!='']
            if a[1]>=-13 and a[1]<=-1:
                print (a[0],a[1])
    

    Edit: If you're working with table data I would suggest trying out Pandas, it's really helpful in these situations.