【问题标题】:KeyError while reading a CSV file in Python在 Python 中读取 CSV 文件时出现 KeyError
【发布时间】:2022-01-24 13:37:25
【问题描述】:

我试图将物体(准确地说是光学叉)的下落绘制为时间的函数,以验证万有引力定律确实是 9.81。不同的数据应该代表每个插槽的通道。不同的狭缝相距1厘米,共有11条狭缝。我使用 Arduino 设置测量了这些数据,并绘制了图表并与 Python 匹配。我有一个 CSV 文件中的数据,但是当我运行我的代码时,我得到了一个

KeyError: 'T (s)'

我不明白,因为我的 DataFrame 中存在列 T (s)。

这是我的名为“Test.csv”的 CSV 文件(我指定我不想选择 T 列的第一个和最后一个值(即 3.514 和 3.636)并且我不想阅读距离列):

T (s) Distance (m)
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()

你知道这个错误是从哪里来的吗?

【问题讨论】:

  • 显然 T(s) 不在您的数据中。检查列名。也许之前或之后有一个空格。
  • @kağanhazalkoçdemir 我不明白你的意思,因为我们可以看到 T (s) 是我的 CSV 文件第一列的名称
  • 获取T(s)的列名并选中。我明白,但显然,还有别的东西。可能是空格或我的坏:)
  • 它看起来不像逗号分隔的数据。当您执行data.keys() 时,您会得到预期键的列表吗?
  • 请在打开数据文件后添加一个 print(data.info()) 并让我们知道这一行的输出。

标签: python pandas anaconda spyder keyerror


【解决方案1】:

实际上查看 df.info 似乎分隔符,至少从列名来看,是一个分号。列名也应该是“时间(s)”。请尝试:

data=pd.read_csv("Test.csv",sep=";")
z = -0.01 * np.linspace(1, 11, 11)    
x = data['Time (s)']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-12
    相关资源
    最近更新 更多