如何在 Pandas 中獲取 Series 的幾行資料?
Pandas 中的 Series 的索引用於訪問 Series 中的元素,同樣,我們也可以使用**切片**技術從 Series 物件中獲取一組值。換句話說,我們可以從 Pandas Series 物件中檢索子集。此過程類似於 NumPy 陣列切片。
可以透過定義 Series 的起始和終點索引值來檢索一些元素集。
示例
# importing required packages
import pandas as pd
import numpy as np
# creating pandas Series object
series = pd.Series(np.random.rand(10))
print(series)
print('
Retrieve first 3 elements')
# accessing elements by using index values
print(series[0:3])
print('
Retrieve 3 elements from middle')
# accessing elements by using index values
print(series[4:7])解釋
在這個例子中,我們建立了一個帶有位置索引值的 Series 物件,資料是使用 NumPy 隨機模組生成的隨機值。
在這裡,我們透過定義起始和結束值(使用 Series 名稱“series[start:end]”)從 Series 物件中檢索了一組行。
輸出
0 0.445380 1 0.644535 2 0.961340 3 0.242597 4 0.272414 5 0.126234 6 0.579381 7 0.358938 8 0.542832 9 0.476023 dtype: float64 Retrieve first 3 elements 0 0.445380 1 0.644535 2 0.961340 dtype: float64 Retrieve 3 elements from middle 4 0.272414 5 0.126234 6 0.579381 dtype: float64
輸出
上面程式碼塊的第一部分表示整個 Series 物件,第二部分是透過定義從 0 到 3 的索引範圍(series[0:3])切片的子集值,同樣,我們透過定義 4 到 7 之間的索引範圍(series[4:7])檢索了另一個子集,它在上面程式碼塊的最後部分表示。
示例
我們還可以切片標籤索引的 Series 物件,下面的示例將解釋如何切片具有標籤索引的 Series。
# importing required packages
import pandas as pd
# creating pandas Series object
series = pd.Series({'B':'black', 'W':'white','R':'red', 'Bl':'blue','G':'green'})
print(series)
print('
Retrieve first 2 elements')
# accessing elements by using index values
print(series[0:2])
print('
Retrieve elements by using label index')
# accessing elements by using label index
print(series['W':'G'])解釋
在上面的示例中,我們建立了一個帶有標籤索引的 Series 物件,並且我們使用了位置索引值以及標籤索引值應用了切片。
透過指定從 0 到 2 的位置索引(series[0:2])訪問了 Series 中的 2 個元素。同樣,我們也指定了標籤索引(例如 series[‘W’:’G’])。
輸出
B black W white R red Bl blue G green dtype: object Retrieve first 2 elements B black W white dtype: object Retrieve elements by using label index W white R red Bl blue G green dtype: object
上面程式碼塊是整個 Series 物件的輸出,以及透過在標籤索引 Series 物件上使用位置索引和標籤索引訪問的一些行。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP