如何从单个目录读取多个csv文件并在Python中分别对其进行图形处理? [英] How can I read multiple csv files from a single directory and graph them separately in Python?
问题描述
我想从目录中读取csv文件并对其进行绘制,并且能够单击箭头按钮以逐步浏览图并查看其他图。我想指定哪一列,并能够像在下面的代码中一样对它进行标题。
I want to read csv files from a directory and plot them and be able to click the arrow button to step through a plot and look at a different plot. I want to specify which column and be able to title it as well as I have in the code below as well.
我能够读取csv文件并绘制一个具有特定列的单个图,但是我不确定如何使用多个列。我已经尝试过glob,但是没有用,我不想将它们连接到单个csv文件中。我在下面提供了我的代码。任何帮助,将不胜感激。谢谢。
I am able to read the csv file and plot a single plot with specific columns but I am not sure how to do it with multiple. I've tried glob but it didn't work, I do not want to concatenate them to a single csv file. I have provided my code below. Any help would be appreciated. Thank you.
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()
推荐答案
您只需要在所有文件上添加一个 for
循环并使用 glob
进行收集
You just need to add a for
loop over all the files and use glob
to collect them.
例如,
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()
在 for
循环中保留 plt.show()
可以确保绘制每个图。搜索如何在python中为绘图添加标题来查找其他问题的答案应该很容易。
Keeping plt.show()
inside the for
loop will ensure each plot is plotted. It should be pretty easy to search for 'How to add a title to a plot in python' for answers to your other questions.
这篇关于如何从单个目录读取多个csv文件并在Python中分别对其进行图形处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!