如何在Pandas中獲取序列的長度、大小和形狀?
有多種方法可以獲取pandas Series物件中存在的元素數量。pandas Series建構函式提供多個屬性和方法來確定Series物件的特徵。
在下面的示例中,我們將學習pandas Series物件的size和shape屬性。size屬性將返回一個整數,表示Series物件中存在的總元素數,其作用類似於Python的len()函式。
shape屬性將返回一個包含兩個元素的元組,這兩個元素是整數,分別表示pandas資料結構物件的行數和列數。由於pandas Series是具有標記索引的一維pandas資料結構物件,因此shape屬性的輸出將返回一個包含單個整數元素的元組,表示pandas Series物件的行數。
示例
# importing pandas packages
import pandas as pd
# creating pandas Series object
series = pd.Series(list('ABCDEFGH'))
print(series)
# to get length of the series
print('Length of series:',len(series))
print('Size of the Series:', series.size)
print('The shape of series:',series.shape)解釋
這裡我們建立了一個簡單的包含字串資料的Series物件,資料為A、B、C、D、E、F、G、H,索引值為0、1、2到7。
使用Python的len()函式可以獲取Series物件的長度,size和shape屬性將返回元素計數和Series的維度。
輸出
0 A 1 B 2 C 3 D 4 E 5 F 6 G 7 H dtype: object Length of series: 8 Size of the Series: 8 The shape of series: (8,)
整數和字母列是Series物件輸出的表示,此Series的資料型別是物件資料型別。我們可以在上面的輸出塊中看到len()函式、size屬性和shape屬性的輸出。
示例
# importing pandas packages
import pandas as pd
# creating pandas Series object
series = pd.Series({'B':'black', 'W':'white', 'R':'red', 'G':'green'})
print(series)
# to get length of the series
print('Length of series:',len(series))
print('Size of the Series:', series.size)
print('The shape of series:',series.shape)解釋
Series物件是使用帶有鍵值對的字典建立的,在這個例子中,我們使用pandas Series屬性驗證了Series物件的長度、大小和形狀。
輸出
B black W white R red G green dtype: object Length of series: 4 Size of the Series: 4 The shape of series: (4,)
可以在上面的輸出塊中看到我們的Series物件的長度、大小和形狀。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP