我正在處理有關CSV文件的項目。我幾乎沒有開始學習Python和它的奧祕。我有一段看起來在一個文件夾中的代碼,獲取所有「.csv」文件(或者在這種情況下爲「.txt」,這就是我如何找到所有海量數據)並讀出它的數據。我導入CSV與pandas
(它有2列,Time
和Amplitude
)我想繪製兩列。我知道情節是怎麼樣的(數據被繪製在MATLAB中,但我的工作是爲python創建一個軟件)。我試圖用這個link但我不知道如何使它知道我是Time
和Y-axis
是Amplitude
在Python中繪製CSV數據
這是我整個代碼到目前爲止
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()
PS:當我嘗試繪圖它給了我:`KeyError:'時間'。
編輯
使用pandas
2.fixed的eCopy錯誤的情節代碼
新的編輯後,我不再獲得1.converted的data_tables
值float
的KeyError
但Time
和Ampl
給出另一個錯誤,指出指數預計爲integers
而不是str
或slices
,它接受的唯一值是1
或0
,任何其他值是out of index
聽起來像是你的'表'字典沒有關鍵的'時間'。目錄中正在分析的所有文件是否有「時間」列?文件列名是否作爲字典鍵傳遞給'tables'? – stephenlechner
@stephenlechner'tables'不是'dict',它是'pandas.DataFrame'。 –
是不是'表格'只是循環中的臨時變量?我希望你使用'data_tables'中的一個表進行繪圖。順便說一句,你可以通過使用'pathlib.Path'來簡化大量的路徑處理。例如,這個循環可以替換爲'for file in Path()。glob('**/*。txt'):'。 –