- 使用
p = Path(...): p → WindowsPath('so_data/files')
-
files = p.rglob(...) 产生与模式匹配的所有文件
-
file[0] → WindowsPath('so_data/files/data_1.csv')
-
p.parent / 'plots' / f'{file.stem}.png' → WindowsPath('so_data/plots/data_1.png')
-
p.parent → WindowsPath('so_data')
-
file.stem → data_1
- 这假定所有目录都存在。不包括目录创建/检查。
- 此示例使用
pandas,OP 也是如此。
- 使用
pandas.DataFrame.plot 绘制,它使用matplotlib 作为默认后端。
- 使用
.iloc 指定列,然后x=0 将始终是x 轴数据,基于给定的示例数据。
- 在
python 3.8.11、pandas 1.3.2、matplotlib 3.4.3中测试
import pandas as pd
import matplotlib.pyplot as plt
from pathlib import Path
p = Path('so_data/files') # specify the path to the files
files = p.rglob('data_*.csv') # generator for all files based on rglob pattern
for file in files:
df = pd.read_csv(file, header=0, sep=',') # specify header row and separator as needed
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(7, 5))
df.iloc[:, [0, 1]].plot(x=0, ax=ax1) # plot 1st x/y pair; assumes x data is at position 0
df.iloc[:, [2, 3]].plot(x=0, ax=ax2) # plot 2nd x/y pair; assumes x data is at position 0
fig.savefig(p.parent / 'plots' / f'{file.stem}.png')
plt.close(fig) # close each figure, otherwise they stay in memory
样本数据
- 这是用于测试绘图代码
- 手动创建
so_data/files 目录。
df = pd.DataFrame({'x1': [5.0, 6.0, 7.0, 8.0, 9.0], 'y1': [60, 70, 80, 90, 100], 'x2': [5.5, 6.5, 7.5, 8.5, 9.5], 'y2': [500, 600, 700, 800, 900]})
for x in range(1, 1001):
df.to_csv(f'so_data/files/data_{x}.csv', index=False)
备用答案
- 此答案针对存在许多连续 x/y 列对的情况
-
df.column 创建一个列数组,可以分块成对
- 对于连续的列对,这个answer 有效
-
list(zip(*[iter(df.columns)]*2)) → [('x1', 'y1'), ('x2', 'y2')]
- 如有必要,使用其他模式创建列对
- 使用
.loc,因为会有列名,而不是.iloc 作为列索引。
p = Path('so_data/files')
files = p.rglob('data_*.csv')
for file in files:
df = pd.read_csv(file, header=0, sep=',')
col_pair = list(zip(*[iter(df.columns)]*2)) # extract column pairs
fig, axes = plt.subplots(len(col_pair), 1) # a number of subplots based on number of col_pairs
axes = axes.ravel() # flatten the axes if necessary
for cols, ax in zip(col_pair, axes):
df.loc[:, cols].plot(x=0, ax=ax) # assumes x data is at position 0
fig.savefig(p.parent / 'plots' / f'{file.stem}.png')
plt.close(fig)