如何从单个目录中读取多个csv文件并在Python中分别对其进行图形处理?

时间:2019-05-06 16:02:37

标签: python pandas csv matplotlib glob

我想从目录中读取csv文件并对其进行绘制,并且能够单击箭头按钮以逐步浏览图并查看其他图。我想指定哪一列,并能够像在下面的代码中一样对其进行标题。

我能够读取csv文件并绘制带有特定列的单个图,但是我不确定如何使用多个列。我已经尝试了glob,但是它没有用,我不想将它们连接到单个csv文件中。我在下面提供了我的代码。任何帮助,将不胜感激。谢谢。

import pandas as pd
import matplotlib.pyplot as plt


cols_in = [1, 3]
col_name = ['Time (s), Band (mb)']

df = pd.read_csv("/user/Desktop/TestNum1.csv", usecols = cols_in, names = 
col_name, header = None)
fig, ax = plt.subplots()
my_scatter_plot = ax.scatter(df["Time (s)"], df["Band (mb)"])

ax.set_xlabel("Time (s)")
ax.set_ylabel("Band (mb)")
ax.set_title("TestNum1")
plt.show()

1 个答案:

答案 0 :(得分:0)

您只需要在所有文件上添加for循环并使用glob来收集它们。

例如,

import pandas as pd
import matplotlib.pyplot as plt
import glob


cols_in = [1, 3]
col_name = ['Time (s), Band (mb)']

# Select all CSV files on Desktop
files = glob.glob("/user/Desktop/*.csv")

for file in files:

    df = pd.read_csv(file, usecols = cols_in, names = 
    col_name, header = None)

    fig, ax = plt.subplots()
    my_scatter_plot = ax.scatter(df["Time (s)"], df["Band (mb)"])

    ax.set_xlabel("Time (s)")
    ax.set_ylabel("Band (mb)")
    ax.set_title("TestNum1")
    plt.show()

plt.show()循环内保留for将确保绘制每个图。搜索“如何在python中为绘图添加标题”来查找其他问题的答案应该很容易。