【发布时间】:2022-01-24 01:55:14
【问题描述】:
我试图将物体(准确地说是光学叉)的下落绘制为时间的函数,以验证万有引力定律确实是 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()
【问题讨论】:
-
重塑数据是什么意思?
-
-
@SibtainReza 那么这就是你首先应该说的,因为这里的问题是 OP 应该通过
t[0]他们将t传递给op.curve_fit- 说你只是让它按原样工作,而您做了其他事情来避免 OP 提到的问题是无益的,并且可能会使其他人拒绝回答。不要。