Nikitau
Nikitau

Reputation: 371

Loop through csv file and plot columns?

I'm having so much trouble and I'd like if I could get a hand. I'm trying to read through a csv file and extract the columns and plot whatever columns are listed in column_index, which is actually an input provided to the user and can be changed.

Here is a link of my pastebin of the .csv file, and this is my attempt:

with open('./P14_data.csv', 'rb') as csvfile:
        data = csv.reader(csvfile, delimiter=',')

        #retrieves rows of data and saves it as a list of list
        x = [row for row in data]

        #forces list as array to type cast as int
        int_x = np.array(x, int)

        column_index = [1,2,3]
        column_values = np.empty(0)

        for col in column_index:
        #loops through array
            for array in range(len(int_x)):
        #gets correct column number
                column_values = np.append(column_values,np.array(int_x[array][col-1]))
            plt.plot(column_values)

However, this only graphs one line for all 3 columns when I want 3 different lines for the columns:

enter image description here

Upvotes: 2

Views: 1209

Answers (1)

falsetru
falsetru

Reputation: 369064

Reset column_values before the inner loop. Otherwise, values are keep appended to the same list.

column_index = [1,2,3]
for col in column_index:
    column_values = np.empty(0)  # <--- reset for each line chart.
    for array in range(len(int_x)):
        column_values = np.append(column_values, np.array(int_x[array][col-1]))
    plt.plot(column_values)

enter image description here

Upvotes: 1

Related Questions