如果指定的索引不存在于 Python Pandas 系列中会发生什么?


当索引值被自定义时,可以使用 `series_name[‘index_value’]` 来访问它们。传递给 series 的 `‘index_value’` 会尝试与原始 series 匹配。如果找到,相应的数

当尝试访问的索引不存在于 series 中时,会抛出一个错误。如下所示。

示例

 在线演示

import pandas as pd
my_data = [34, 56, 78, 90, 123, 45]
my_index = ['ab', 'mn' ,'gh','kl', 'wq', 'az']
my_series = pd.Series(my_data, index = my_index)
print("The series contains following elements")
print(my_series)
print("Accessing elements using customized index")
print(my_series['mm'])

输出

The series contains following elements
ab  34
mn  56
gh  78
kl  90
wq  123
az  45
dtype: int64
Accessing elements using customized index
Traceback (most recent call last):
KeyError: 'mm'

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

解释

  • 导入所需的库,并为方便使用赋予别名。

  • 创建一个数据值列表,稍后将其作为参数传递给 `pandas` 库中存在的 `Series` 函数。

  • 接下来,将稍后作为参数传递的自定义索引值存储在一个列表中。

  • 创建 series,并将索引列表和数据作为参数传递给它。

  • 在控制台上打印 series。

  • 由于索引值是自定义的,因此它们用于像 `series_name[‘index_name’]` 那样访问 series 中的值。

  • 在 series 中搜索它,但当找不到时,它会抛出一个 `KeyError`。

  • 然后在控制台上打印它。

更新于:2020年12月10日

402 次浏览

启动您的 职业生涯

完成课程获得认证

开始
广告