如何在Pandas DataFrame中檢查資料型別?


為了檢查pandas DataFrame中的資料型別,我們可以使用"dtype"屬性。該屬性返回一個包含每一列資料型別的序列。

DataFrame的列名作為結果序列物件的索引,相應的資料型別作為序列物件的取值。

如果任何列儲存了混合資料型別,則整列的資料型別將顯示為object dtype

示例1

應用pandas dtype屬性並驗證DataFrame物件中每一列的資料型別。

# importing pandas package
import pandas as pd

# create a Pandas DataFrame
df = pd.DataFrame({'Col1':[4.1, 23.43], 'Col2':['a', 'w'], 'Col3':[1, 8]})

print("DataFrame:")
print(df)

# apply the dtype attribute
result = df.dtypes

print("Output:")
print(result)

輸出

輸出如下所示:

DataFrame:
      Col1 Col2 Col3
0     4.10    a    1
1    23.43    w    8

Output:
Col1    float64
Col2     object
Col3      int64
dtype: object

在這個輸出塊中,我們可以注意到,Col1的資料型別為float64Col2的資料型別為objectCol3儲存的是整數(int64)型別資料。

示例2

現在,讓我們將dtype屬性應用於另一個Pandas DataFrame物件。

# importing pandas package
import pandas as pd

# create a Pandas DataFrame
df = pd.DataFrame({'A':[41, 23, 56], 'B':[1, '2021-01-01', 34.34], 'C':[1.3, 3.23, 267.3]})

print("DataFrame:")
print(df)

# apply the dtype attribute
result = df.dtypes

print("Output:")
print(result)

輸出

輸出如下:

DataFrame:
              A       B       C
0            41       1    1.30
1 23 2021-01-01    3.23
2            56   34.34  267.30

Output:
A      int64
B     object
C    float64
dtype: object

對於給定的DataFrame,列B儲存了混合資料型別的值,因此該特定列的結果dtype表示為object dtype。

更新於:2023年8月29日

21.1萬+ 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告