解釋在 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 還包含索引功能,其中可以使用運算子“:”來指定需要訪問/顯示的元素範圍。
然後將其列印到控制檯。
廣告