pandas DataFrame 中的 ndim 是什麼?


ndim 是 pandas DataFrame 中的一個屬性,用於獲取給定 DataFrame 物件的維度整型/數字表示形式。

眾所周知,pandas DataFrame 是一個二維資料結構,用於以表格格式儲存資料。無論行和列的長度或型別如何,DataFrame 的維度都不受影響。

pandas DataFrame 的 ndim 屬性的輸出始終為 2。

示例 1

在以下示例中,我們已將 ndim 屬性應用於 pandas DataFrame 物件“df”,此 DataFrame 是使用單個列“Col1”建立的。

# importing pandas packages
import pandas as pd

L = list('ABCDEFGH')

# creating pandas DataFrame
df = pd.DataFrame(L, columns=['col1'])

print('DataFrame:')
print(df)

# apply ndim property to get the dimensions
print('Result:', df.ndim)

輸出

輸出如下所示 -

DataFrame:
  col1
0    A
1    B
2    C
3    D
4    E
5    F
6    G
7    H

Result: 2

在以上輸出塊中,值 2 表示給定 DataFrame 的維度。

示例 2

讓我們使用另一個 pandas DataFrame 物件並應用 ndim 屬性以獲取維度。

# importing pandas package
import pandas as pd

# create a Pandas DataFrame
df = pd.DataFrame({'Country':['Brazil','Canada','New Zealand','Iceland', 'India', 'Sri Lanka', 'United States'],
'Capital': [ 'Belmopan','Ottawa','Wellington','Reykjavik', 'New Delhi','Colombo', 'Washington D.C']})

print("DataFrame:")
print(df)

# apply ndim property to get the dimensions
print('Result:', df.ndim)

輸出

輸出如下所示 -

DataFrame:
       Country         Capital
0       Brazil        Belmopan
1       Canada          Ottawa
2  New Zealand      Wellington
3      Iceland       Reykjavik
4        India       New Delhi
5     Sri Lanka        Colombo
6 United States Washington D.C
Result: 2

對於此示例,ndim 屬性還為給定 DataFrame 返回了 2。

更新於: 2022 年 3 月 8 日

2K+ 次瀏覽

開啟您職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.