循环csv文件和打印列?

2024-04-24 12:18:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这么多麻烦,我想找个人帮忙。我试图读取一个csv文件,提取列并绘制column_index中列出的任何列,这实际上是提供给用户的一个输入,可以更改。在

这是我的.csv文件的一个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


Tags: 文件csvcsvfileinfordataindexas
1条回答
网友
1楼 · 发布于 2024-04-24 12:18:23

在内部循环之前重置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

相关问题 更多 >