解释在 Python 中访问序列数据结构中数据的不同方法?
能够索引元素并使用其位置索引值访问它们,在我们需要访问特定值时非常有用。
让我们看看如何索引序列数据结构以从特定索引获取值。
示例
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("The second element (zero-based indexing)")
print(my_series[2])
print("Elements from 2 to the last element are")
print(my_series[2:])输出
The series contains following elements ab 34 mn 56 gh 78 kl 90 wq 123 az 45 dtype: int64 The second element (zero-based indexing) 78 Elements from 2 to the last element are gh 78 kl 90 wq 123 az 45 dtype: int64
解释
导入了所需的库,并为方便使用赋予了别名。
创建了一个数据值列表,稍后将其作为参数传递给 'pandas' 库中的 'Series' 函数。
接下来,自定义索引值存储在一个列表中。
使用 Python 的索引功能从序列中访问特定索引元素。
Python 还包含索引功能,其中可以使用运算符“:”来指定需要访问/显示的元素范围。
然后将其打印到控制台。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP