【发布时间】:2017-05-07 17:07:40
【问题描述】:
我正在做一个关于 CSV 文件的项目。我刚刚开始学习 python 及其奥秘。我有这段代码,它在文件夹中查找,获取所有“.csv”文件(在这种情况下为“.txt”,这就是我找到所有海量数据的方式)并读出其数据。在我使用pandas(它有两列,Time 和Amplitude)导入 CSV 之后,我想绘制这两列。我已经知道绘图的样子(数据是在 MATLAB 中绘制的,但我的工作是为 python 创建一个软件)。我尝试使用这个link,但我不知道如何让它知道我的X-axis 是Time 而Y-axis 是Amplitude
到目前为止,这是我的全部代码
import pandas as pd
import os
import tkinter as tk
from tkinter.filedialog import askdirectory
import matplotlib.pyplot as plt
print ("Please choose the path to the CSV Files: ")
root = tk.Tk()
root.withdraw()
root.attributes('-topmost', True)
path = askdirectory()
print("\nThe chosen folder is: " + path)
tmp_paths=[]
data_tables=[]
data_paths=[]
file_ext=[]
file_name=[]
sep_name=[]
for root, dirs, files in os.walk(path):
for file in files:
if file.endswith(".txt"):
tmp_paths=os.path.join(root,file) #
tables=pd.read_csv(tmp_paths, header=5, sep=' ',converters={"Time":float, "Ampl":float})
data_tables.append(tables)
data_paths.append(tmp_paths)
file_ext=[name.split("\\",1)[1] for name in data_paths]
file_name=[name.split(".txt",1)[0] for name in file_ext]
sep_name=[name.split("-",6) for name in file_name]
plt.plot(data_tables[1],data_tables[0])
plt.show()
P.S:当我尝试绘图时,它给了我:`KeyError: 'Time'。
编辑
1.使用pandas 将data_tables 值转换为float
2.修复情节代码中的ecopy错误
在新的编辑之后,我不再得到 KeyError 但 Time 和 Ampl 给出另一个错误,指出索引应该是 integers 而不是 str 或 slices 以及它的唯一值接受为1 或0,任何其他值为out of index
【问题讨论】:
-
听起来你的
tables字典没有“时间”键。正在解析的目录中的所有文件是否都有“时间”列?文件列名是否作为字典键传递给tables? -
@stephenlechner
tables不是dict,而是pandas.DataFrame。 -
tables不应该只是循环中的一个临时变量吗?我希望您使用data_tables中的一张表进行绘图。顺便说一句,您可以使用pathlib.Path简化很多路径处理。例如,该循环可以仅替换为for file in Path().glob('**/*.txt'):。 -
我可以看看`table.info()`的输出吗
-
@stovfl 这是
table.info()显示的内容:<class 'pandas.core.frame.DataFrame'> RangeIndex: 1000 entries, 0 to 999 Data columns (total 2 columns): -2.50301e-006 1000 non-null float64 -69.7396 1000 non-null float64 dtypes: float64(2) memory usage: 15.7 KB
标签: python csv matplotlib