如何检查 pandas DataFrame 中的数据类型?

阅读 143 收藏 0 点赞 0 评论 0

要检查 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 有 float64 类型的数据,Col2 有目标数据,而“Col3”列存储了整数类型的数据。

示例 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。

评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号