python - 函数 np.interp 和 pandas Python 出错

标签 python pandas csv ubuntu

有人可以建议如何纠正这个问题?

Traceback (most recent call last):
  File "/home/morpheus/.local/lib/python3.8/site-packages/pandas/core/indexes/base.py", line 3080, in get_loc
    return self._engine.get_loc(casted_key)
  File "pandas/_libs/index.pyx", line 70, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/index.pyx", line 101, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/hashtable_class_helper.pxi", line 975, in pandas._libs.hashtable.Float64HashTable.get_item
  File "pandas/_libs/hashtable_class_helper.pxi", line 982, in pandas._libs.hashtable.Float64HashTable.get_item
KeyError: 0.5702862420640393
上述异常是以下异常的直接原因:
Traceback (most recent call last):
  File "BatchNTC_dev.py", line 83, in <module>
    tau = ignitionDelay(timeHistory.loc[t], T_rise)
  File "/home/morpheus/.local/lib/python3.8/site-packages/pandas/core/indexing.py", line 895, in __getitem__
    return self._getitem_axis(maybe_callable, axis=axis)
  File "/home/morpheus/.local/lib/python3.8/site-packages/pandas/core/indexing.py", line 1124, in _getitem_axis
    return self._get_label(key, axis=axis)
  File "/home/morpheus/.local/lib/python3.8/site-packages/pandas/core/indexing.py", line 1073, in _get_label
    return self.obj.xs(label, axis=axis)
  File "/home/morpheus/.local/lib/python3.8/site-packages/pandas/core/generic.py", line 3739, in xs
    loc = index.get_loc(key)
  File "/home/morpheus/.local/lib/python3.8/site-packages/pandas/core/indexes/numeric.py", line 395, in get_loc
    return super().get_loc(key, method=method, tolerance=tolerance)
  File "/home/morpheus/.local/lib/python3.8/site-packages/pandas/core/indexes/base.py", line 3082, in get_loc
    raise KeyError(key) from err
KeyError: 0.5702862420640393
这是原始脚本
import pandas as pd
import numpy as np

import time
import csv
import cantera as ct
print('Running Cantera version: ' + ct.__version__)


import matplotlib.pyplot as plt

plt.rcParams['axes.labelsize'] = 18
plt.rcParams['xtick.labelsize'] = 12
plt.rcParams['ytick.labelsize'] = 12
plt.rcParams['figure.autolayout'] = True

plt.style.use('ggplot')
plt.style.use('seaborn-pastel')

gas = ct.Solution('Seiser.cti')

# Define the reactor temperature and pressure
reactor_temperature = 1000  # Kelvin
reactor_pressure = 101325  # Pascals

gas.TP = reactor_temperature, reactor_pressure

# Define the fuel, oxidizer and set the stoichiometry
gas.set_equivalence_ratio(phi=1.0, fuel="nc7h16", oxidizer={"o2": 1.0, "n2": 3.76})

# Create a batch reactor object and add it to a reactor network
# In this example, the batch reactor will be the only reactor
# in the network
r = ct.IdealGasReactor(contents=gas, name="Batch Reactor")
reactor_network = ct.ReactorNet([r])
谢谢
def ignitionDelay(states, dT):

    """

    This function computes the ignition delay from the occurence of the

    peak in species' concentration.

    """
    idt = np.interp(states.T[0]+dT, states.T, states.t)#

    return idt

T_rise=10.


r = ct.IdealGasReactor(contents=gas, name='Batch Reactor')
reactorNetwork = ct.ReactorNet([r])

# now compile a list of all variables for which we will store data
stateVariableNames = [r.component_name(item) for item in range(r.n_vars)]

# use the above list to create a DataFrame
timeHistory = pd.DataFrame(columns=stateVariableNames)

t0 = time.time()

# This is a starting estimate. If you do not get an ignition within this time, increase it
estimatedIgnitionDelayTime = 0.1
t = 0

counter = 1;
while(t < estimatedIgnitionDelayTime):
    t = reactorNetwork.step()
    if (counter%10 == 0):
        # We will save only every 10th value. Otherwise, this takes too long
        # Note that the species concentrations are mass fractions
        timeHistory.loc[t] = reactorNetwork.get_state()
    counter+=1
    
timeHistory.to_csv("time_historyBATCH.csv")

# We will use the 'oh' species to compute the ignition delay
tau = ignitionDelay(timeHistory.loc[t], T_rise)

#Toc
t1 = time.time()

print('Computed Ignition Delay: {:.3e} seconds. Took {:3.2f}s to compute'.format(tau, t1-t0))

# If you want to save all the data - molefractions, temperature, pressure, etc

最佳答案

在不了解您的代码/所需行为的更多信息的情况下, t 的值在您的 while 循环期间递增。 while 循环继续,直到 t 大于估计的IgnitionDelayTime。
我想这意味着 timeHistory 中的值仅包含小于此估计的 IgnitionDelayTime 的 t 值。但是,t 将再增加一次,直到大于estimatedIgnitionDelayTime,因此当您尝试访问timeHistory.loc[t] 时,t 的值(大于estimatedIgnitionDelayTime)不在您的timeHistory Dataframe 的索引中,从而导致KeyError .
尝试保存 t 的最后一个值,或修改您的 while 循环或数据帧以避免此错误

关于python - 函数 np.interp 和 pandas Python 出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68396022/

相关文章:

python - 谷歌应用引擎 : new version doesn't appear

python - SQL 数据库是否比大型 Pandas 数据框的内存/性能效率更高?

c# - 使用 CSVHelper 如何使用子项列表反序列化 CSV

powershell - 使用 Powershell 对 CSV 文件进行排序

csv - Coldfusion CSV 到电子表格

嵌套if语句的Python单元测试

python - 扭曲的task.LoopingCall在循环中定义回调时会弄乱它们

python - 运行时错误 : maximum recursion depth exceeded with Python 3. 2 pickle.dump

python - 将列表设置为 Pandas 数据框列中的值

python - 从嵌套 json 列表中展平 Pandas DataFrame