循环通过csv文件和绘图列?

时间:2017-05-04 03:53:23

标签: python python-2.7 csv matplotlib

我遇到了这么多麻烦,如果能伸出援助之手,我想知道。我正在尝试通读csv文件并提取列并绘制column_index中列出的任何列,这实际上是提供给用户的输入并且可以更改。

以下是我的.csv文件的pastebin的link,这是我的尝试:

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)

但是,当我想要3列不同的列时,这只会为所有3列绘制一行:

enter image description here

1 个答案:

答案 0 :(得分:1)

在内循环之前重置column_values。否则,值将保留在同一列表中。

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