我試圖將物體(準確地說是光叉)的下落繪制為時間的函式,以驗證萬有引力定律確實是 9.81。不同的資料應該代表每個插槽的段落。不同的狹縫間隔1厘米,總共有11個狹縫。我使用 Arduino 設定測量了這些資料,并繪制了圖形并與 Python 擬合。我有一個 CSV 檔案中的資料,但是當我運行我的代碼時,我得到一個
KeyError: 'T (s)'
我不明白,因為列 T (s) 存在于我的 DataFrame 中。
這是我的名為“Test.csv”的 CSV 檔案(我指定我不想選擇 T 列的第一個和最后一個值(即 3.514 和 3.636),并且我不想讀取距離列) :
| 時間(秒) | 距離(米) |
|---|---|
| 3.514 | 0.000 |
| 3.524 | 0.010 |
| 3.536 | 0.020 |
| 3.548 | 0.030 |
| 3.562 | 0.040 |
| 3.574 | 0.050 |
| 3.582 | 0.060 |
| 3.592 | 0.070 |
| 3.6 | 0.080 |
| 3.61 | 0.090 |
| 3.618 | 0.100 |
| 3.626 | 0.110 |
| 3.636 | 0.120 |
這是我的代碼:
import numpy as np # For the calculation
import pandas as pd # To read files
import matplotlib.pyplot as plt # To draw curves
import scipy.optimize as opt # For the adjustment
# Raw data
data = pd.read_csv("Test.csv") # Opening the data file
z = -0.01 * np.linspace(1, 11, 11)
x = data['T (s)']
x_util = np.array(x[3.524:3.626]) # extracts data between 3.524 and 3.626 s
# Definition of the free fall function
g = 9.81 # the acceleration of gravity
def f(x_util,t0,h0): # Definition of the fitting function
return -0.5*g*(x_util-t0)**2 h0
# Data adjustment
init_param = [0 , 0] # Initial values t0=0, h0=0
final_param , var = opt.curve_fit(f,x_util,z,init_param)
# Optimal function
tt = np.linspace(final_param[0], 100e-3,100)
hh = f(tt, *final_param) # Reconstruction of the fitted curve
# Plot of analyzed data
plt.clf() # Plot of data and fit
plt.xlabel("Time (s)")
plt.ylabel("Height (m)")
legend = "t0 = %f ms, h0 = %f centimeter " % (final_param[0]*1000,final_param[1]*100)
plt.plot(tt,hh,"r--",label=legend) # The adjustment
plt.plot(x_util,z,"bo", label="Data") # The data
plt.legend()
你知道這個錯誤可能來自哪里嗎?
uj5u.com熱心網友回復:
實際上查看 df.info 似乎分隔符,至少從列名來看,是一個分號。列名也應該是“時間(秒)”。請試試:
data=pd.read_csv("Test.csv",sep=";")
z = -0.01 * np.linspace(1, 11, 11)
x = data['Time (s)']
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/392039.html
