我試圖將物體(準確地說是光叉)的下落繪制為時間的函式,以驗證萬有引力定律確實是 9.81。不同的資料應該代表每個插槽的段落。不同的狹縫間隔1厘米,總共有11個狹縫。我使用 Arduino 設定測量了這些資料,并繪制了圖形并與 Python 擬合。我有一個 CSV 檔案中的資料,但是當我運行我的代碼時,出現錯誤“無法強制轉換為系列,長度必須為 1:給定 11”。但是,當我手動一一輸入值而不是讀取檔案時,代碼會起作用并且我得到了這張圖,這正是我所期望的。

這是我使用的指令(我通過手動輸入在每次迭代中添加值,我認為通過在我的 CSV 檔案中做同樣的事情代碼可以作業,但不幸的是它也不起作用)
t = 1e-3 * np.array([3.524,7.06,10.608,14.17,17.744,21.326,24.918,28.518,32.128,35.746,39.372])
代替
t = pd.read_csv("Fall.csv") # Opening the data file
你知道錯誤可能來自哪里嗎?我的意思是為什么當我手動輸入值時代碼有效,但當我嘗試讀取具有完全相同值的檔案時卻無效?我指定我的 CSV 檔案中有 11 個資料。
這是我的初始 CSV 檔案(即沒有在每次迭代時添加值),名稱為“Fall.csv”:
| 3.524 |
| 3.536 |
| 3.548 |
| 3.562 |
| 3.574 |
| 3.582 |
| 3.592 |
| 3.6 |
| 3.61 |
| 3.618 |
| 3.626 |
這是我的完整代碼:
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
t = pd.read_csv("Fall.csv") # Opening the data file
z = -0.01 * np.linspace(1, 11, 11)
# Definition of the free fall function
g = 9.81 # the acceleration of gravity
def f(t,t0,h0): # Definition of the fitting function
return -0.5*g*(t-t0)**2 h0
# Data adjustment
init_param = [0 , 0] # Initial values t0=0, h0=0
final_param , var = opt.curve_fit(f,t,z)
# 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(t,z,"bo", label="Data") # The data
plt.legend()
uj5u.com熱心網友回復:
您的問題來自t. Scipycurve_fit檔案指定,在您的情況下,xdata應該是一個序列,即一維陣列(或多或少)。
但是,由于您的 csv 逐行具有一個值,因此pd.read_csv()將其讀取為 DataFrame,它基本上是一個 2D 陣列。
您可以通過列印來檢查它t.shape,它輸出(11,1),而z.shapeis (11,)。
對于這個問題的多種解決方案,無論是重寫您在一行或致電CSVopt_curve與t[0]挑只的第一列t。這里0要小心,是 DataFrame 的第一列也是唯一一列的名稱,而不是索引。這會給:final_param, var = opt.curve_fit(f, t[0], z)
不過,我會建議第一個解決方案,在讀取資料時直接獲得所需的形狀。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/394340.html
