【问题标题】:Loop through csv file and plot columns?循环遍历 csv 文件并绘制列?
【发布时间】:2017-10-02 02:02:22
【问题描述】:

我遇到了很多麻烦,我希望能帮上忙。我正在尝试读取 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 列绘制一条线:

【问题讨论】:

  • 在 plt.plot() 之前显示 print(int_x)、print(column_values) 和 print(column_values) 的结果

标签: python python-2.7 csv matplotlib


【解决方案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)

【讨论】:

    猜你喜欢
    • 2014-04-10
    • 2018-02-07
    • 2016-09-28
    • 2019-07-21
    • 2019-04-11
    • 2023-02-24
    • 1970-01-01
    • 2021-03-04
    • 1970-01-01
    相关资源
    最近更新 更多