【问题标题】:How to get csv data in python如何在python中获取csv数据
【发布时间】:2021-04-12 15:54:09
【问题描述】:

我已经编写了绘图函数和正文部分,但无法找出获取数据 csv 的必要代码。所以基本上我的代码是:

import random
import matplotlib.pyplot as plt 

def get_data_csv(fn, colx, coly, sep=','):


    return x_data, y_data, x_label, y_label

def plot_graphs(x_data, y_data, x_label, y_label, title, color=None):
    plt.figure()
    #if there are more than one graph to plot in the same figure, same x-axis
    if all(type(arg) == list for arg in [x_data, y_data, y_label]):
        lx = len(x_data)
        if lx > 1 and all(len(arg) == lx for arg in [y_data, y_label]):
            for i in range(lx):
                color = list(random.random() for c in range(3))
                plt.plot(x_data[i], y_data[i], color = color, label = y_label[i])
            plt.xlabel(x_label)
            plt.title(title)
            plt.legend()
        else:
            print('Something get wrong, review your arguments')
    # if there is only one graph to plot
    else:
        plt.plot(x_data, y_data, color=color)
        plt.ylabel(y_label)
        plt.xlabel(x_label)
        plt.title(title)
        plt.xlim([min(x_data), max(x_data)])
    plt.grid('all')
    plt.show()
    
if __name__ == "__main__":
    user_fn = input("Enter CSV filename(s), separated by ',': ")
    user_colx = input("Enter respective x-column(s), separated by ',': ")
    user_coly = input("Enter respective y-column(s), separated by ',': ")
    user_title = input("Enter title: ")
    fn = user_fn.split(',')
    colx = list(int(c) for c in user_colx.split(','))
    coly = list(int(c) for c in user_coly.split(','))
    if len(fn) == 1:
        fn = fn[0]
        x_data, y_data, x_label, y_label = get_data_csv(fn, colx[0], coly[0])
    else:
        x_data, y_data, y_label = [], [], []
        for i in range(len(fn)):
            auxx, auxy, x_label, auxylbl = get_data_csv(fn[i], colx[i], coly[i])
            x_data.append(auxx)
            y_data.append(auxy)
            y_label.append(auxylbl)
    plot_graphs(x_data, y_data, x_label, y_label, user_title, color='black')

如您所见,我无法编写 def get_data_csv 部分。我认为我应该使用 readline() 从文件中获取标题行,之后,我可以使用任何方式获取其他信息 举例说明代码应该如何工作。

Enter CSV filename(s), separated by ',': sinusoid.csv
Enter respective x-column(s), separated by ',': 0
Enter respective y-column(s), separated by ',': 1
Enter title: Sine

这应该可以。我需要帮助

【问题讨论】:

  • 你应该看看pandas,它有一个read_csv 函数可以将csv文件读入一个与matplotlib配合得很好的数据帧。

标签: python python-3.x csv matplotlib plot


【解决方案1】:

我建议你只使用包 csv。这是一个关于如何使用 csv 包的 reader 方法的示例 -

import csv
with open('example.csv', newline='') as fh:
    csvreader = csv.reader(fh, delimiter=',', quotechar='|')

for row in csvreader:
    print(row)

有关更多信息,请参阅此文档:https://docs.python.org/3/library/csv.html

【讨论】:

    【解决方案2】:

    我自己找到了问题的答案。所以我需要的代码是:

    def get_data_csv(fn, colx, coly, sep=','):
        x_data = []
        y_data = []
        with open(fn) as f:
            lines = f.readlines()
            i = 0
            for line in lines:
                line = line[0:-2]
                line = line.split(',')
                if i == 0:
                    x_label = line[colx]
                    y_label = line[coly]
                else:
                    x_value = float(line[colx])
                    x_data.append(x_value)
                    y_value = float(line[coly])
                    y_data.append(y_value)
                i+=1    
        return x_data, y_data, x_label, y_label
    
    

    【讨论】:

      猜你喜欢
      • 2018-04-18
      • 2013-06-20
      • 2021-11-23
      • 2020-10-04
      • 2021-08-27
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多