pandas 如何避免DataFrame中按标签访问行的错误?

ttcibm8c  于 2022-12-02  发布在  其他
关注(0)|答案(1)|浏览(92)

我在访问DataFrame中的行时遇到了麻烦。我的代码和结果如下。是什么问题?请帮助我。

df = pd.read_excel('./eeg_samples/chanlocs67.xlsx',usecols= 
      [0,3,4,5],index_col='labels')
df.index.names = [None] 
print(df.head())
print(df.loc['Fp1'])

结果如下。

X        Y       Z
'Fp1'  83.9171  29.4367  -6.990
'Fz'   58.5120  -0.3122  66.462
'F3'   53.1112  50.2438  42.192
'F7'   42.4743  70.2629 -11.420
'FT9'  14.5673  84.0759 -50.429

Traceback (most recent call last):
File "C:\ProgramData\mne-python\1.2.1_0\lib\site- 
  packages\pandas\core\indexes\base.py", line 3803, in get_loc
    return self._engine.get_loc(casted_key)
File "pandas\_libs\index.pyx", line 138, in 
  pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\index.pyx", line 165, in 
  pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\hashtable_class_helper.pxi", line 5745, in 
  pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas\_libs\hashtable_class_helper.pxi", line 5753, in 
  pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'Fp1'
m1m5dgzv

m1m5dgzv1#

你的索引值是来与周围的引号。所以你需要这样做或修复你的数据在excel文件:

print(df.loc["'Fp1'"])

相关问题