我目前撰寫了一個代碼來運行目錄中的所有 hdf5 檔案,從檔案中列印出表格,為每個表格繪制一個圖形,然后為每個表格吐出曲線下的區域。這是代碼。
import os
directory = '/Users/xx'
for filename in os.listdir(directory):
if filename.endswith(".hdf5"):
xdata = file.get('data')
xdata= np.array(xdata)
xdata_df = pd.DataFrame(xdata)
table1 = pd.DataFrame(xdata_df).reset_index()
print(table1)
x = table1["index"]
y = table1[0]
plt.figure(figsize=(10, 10))
plt.rcParams.update({'font.size': 20})
figure1 = plt.plot(x, y)
# Compute the area using the composite trapezoidal rule.
area = trapz(y, dx=100000)
print("trapz area =", area)
# Compute the area using the composite Simpson's rule.
area = simps(y, dx=100000)
print("simpsons area =", area)
continue
else:
continue
但是,我的代碼似乎在目錄中運行(15 個檔案),但 15 次吐出完全相同的表,曲線下的圖形和區域。有誰知道為什么會發生這種情況?
uj5u.com熱心網友回復:
簡短的回答,要獲得 Y 值,您應該使用y = table1[1], 而不是y = table1[0]. 您將值讀取為x = table1["index"]- 您應該使用x = table1[0]. 另外,您是否意識到您x在撥打電話時trpz()沒有使用simps(). 您正在創建 2 個資料框:xdata_df并且table1僅使用table1- 為什么?如果您只需要 X/Y 資料,則可以直接從資料集中讀取值(不需要資料框)。
注意:上面的代碼缺少h5py.File()打開 H5 檔案。
最后,您可以按如下方式簡化和清理您的代碼:
for filename in glob.iglob(f'{directory}/*.hdf5'):
with h5py.File(filename,'r') as file:
xdata = file['data'][()]
x = xdata[:,0] # or x = file['data'][:,0]
y = xdata[:,1] # or y = file['data'][:,1]
# Compute the area using the composite trapezoidal rule.
area = trapz(y, dx=100000)
print("trapz area =", area)
# Compute the area using the composite Simpson's rule.
area = simps(y, dx=100000)
print("simpsons area =", area)
或者,如果您更喜歡使用資料框:
for filename in glob.iglob(f'{directory}/*.hdf5'):
with h5py.File(filename,'r') as file:
xdata = file['data'][()]
xdata_df = pd.DataFrame(xdata)
table1 = pd.DataFrame(xdata_df).reset_index()
x = table1[0]
y = table1[1]
# Compute the area using the composite trapezoidal rule.
area = trapz(y, dx=100000)
print("trapz area =", area)
# Compute the area using the composite Simpson's rule.
area = simps(y, dx=100000)
print("simpsons area =", area)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/454531.html
