路径优化模型中使用pandas库访问索引的时候出现错误,请帮助!

![![]

大佬们,我在使用pandas库实现路径优化的过程中出现了这种报错,请问怎样可以解除?
我已经尝试过的方法:
1.尝试修改pandas库的代码,但是ai提示pandas库本身没有错误,无需修改,而是在使用pandas访问索引的过程中出现问题
2.尝试使用ai解决问题,并查看dataframe索引,已理解代码中的变量和公式内容,但是由于技术有限,不知道如何检查索引是否在访问时出现错误
3.想尝试查看已有的pandas库以及优化模型是否和pycharm版本适配,但是不知道如何操作
请大佬们帮助,万分感谢!

讨论数量: 2
Jason990420

There's nothing shown about what values of your dataframe and key/index, how people can help ?

A short program that isolates and demonstrates the problem (Do not paste your massive program, but instead 10-20 lines that executable and clearly show the problem)

For example, find all the values of related variables by print statement before exception happed when which statement called. So you can reduce your code to

import pandas as pd

# What values before exception happened
data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
df = pd.DataFrame(data, columns=['A','b','c'])

# exception happened when index by key 1
key = 1
print(df[key])

Exception information

Traceback (most recent call last):
  File "C:\Software\Python\lib\site-packages\pandas\core\indexes\base.py", line 3805, in get_loc
    return self._engine.get_loc(casted_key)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "index.pyx", line 167, in pandas._libs.index.IndexEngine.get_loc
  File "index.pyx", line 196, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\\_libs\\hashtable_class_helper.pxi", line 7081, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas\\_libs\\hashtable_class_helper.pxi", line 7089, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 1

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "D:\test.py", line 9, in <module>
    print(df[key])
          ~~^^^^^
  File "C:\Software\Python\lib\site-packages\pandas\core\frame.py", line 4102, in __getitem__
    indexer = self.columns.get_loc(key)
              ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Software\Python\lib\site-packages\pandas\core\indexes\base.py", line 3812, in get_loc
    raise KeyError(key) from err
KeyError: 1

Then we can find the answer is that there's no key 1 for dataframe df.

3个月前 评论

把你的dataframe多少打印出来一些,或者你的代码提供一下,这个错误很可能是loc[i, t] 的第二个参数t引起的,但是也不是很确定。

3个月前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!