0

I'm trying to make a plot from some data but I get an index out of range error even though the data has 2 columns. Here's the code:

import csv
from matplotlib import pyplot as plt


def getColumn(filename, column):
    results = csv.reader(open(filename), delimiter='\t')
    return [result[column] for result in results]

wavelength = getColumn('Bb69.dat.fix',0)
flux = getColumn('Bb69.dat.fix',1)

plt.figure('Bb69')
plt.xlabel('Wavelength (angstrom)')
plt.ylabel('flux (erg/cm^2/s/angstrom)')
plt.plot(wavelength,flux)
plt.show()

Here is the error

Traceback (most recent call last):

  File "SP12.py", line 14, in <module>

    flux = getColumn('Bb69.dat.fix',1)

  File "SP12.py", line 11, in getColumn

    return [result[column] for result in results]

IndexError: list index out of range

1 Answer 1

1
def getColumn(filename, column):
    results = csv.reader(open(filename), delimiter='\t')
    return [result[column] for result in results]

It is possible, that not all elements of results always contain 2 elements as awaited. For example the csv-file contains empty lines.

Change the last line of the getColumn method to:

    return [result[column] for result in results if len(result) > column]

which is however a risk, because it may return longer lists for lower column if some of the lines do not contain enough fields.

Even better would be:

wavelength = []
flux = []

with open('Bb69.dat.fix') as f:
    for row in csv.reader(f, delimiter='\t'):
        if len(row) >= 2:
            wavelength.append(float(row[0]))
            flux.append(float(row[1]))

This guarantees the same length for wavelength and flux.

Sign up to request clarification or add additional context in comments.

6 Comments

But the file doesn't contain any empty lines, and when I add this I get an valueerror that x and y must have the same dimension(?)
@StevendeRond - then the file has some line(s) with a single element. Check my updated answer.
If I use this the wavelength and flux are both empty. The file does have zeros in the 2nd column and the rest are very small numbers so maby that's the problem?
Empty? You can add a few prints around to see what the code does. Oh and we (both of us) forgot to convert the strings to floats. Now it has been updated.
What does print row between the for and if lines print?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.