如何检查Pandas数据框架的数据类型
Pandas DataFrame是一种二维数据结构,大小可变,是异质的表格数据。在Python中有不同的内置数据类型可用。两个用于检查数据类型的方法是pandas.DataFrame.dtypes和pandas.DataFrame.select_dtypes。
创建一个数据框架来检查Pandas数据框架的数据类型
考虑一个购物商店的数据集,其中有关于客户序列号、客户姓名、所购物品的产品ID、产品成本和购买日期的数据。
#importing pandas as pd
import pandas as pd
# Create the dataframe
df = pd.DataFrame({
'Cust_No': [1,2,3],
'Cust_Name': ['Alex', 'Bob', 'Sophie'],
'Product_id': [12458,48484,11311],
'Product_cost': [65.25, 25.95, 100.99],
'Purchase_Date': [pd.Timestamp('20180917'),
pd.Timestamp('20190910'),
pd.Timestamp('20200610')]
})
# Print the dataframe
df
输出:
使用pandas.DataFrame.dtypes检查Pandas中的数据类型
对于用户来说,检查一个特定的数据集或数据集中的特定列的数据类型可以使用这个方法。该方法返回每一列的数据类型的列表,或者只返回某一特定列的数据类型。
示例 1:
# Print a list datatypes of all columns
df.dtypes
输出:
示例 2:
# print datatype of particular column
df.Cust_No.dtypes
输出:
dtype('int64')
示例 3:
# Checking the Data Type of a Particular Column
df['Product_cost'].dtypes
输出:
dtype('float64')
使用pandas.DataFrame.select_dtypes检查Pandas中的数据类型
与检查数据类型不同,用户可以选择执行检查,以获得特定数据类型的数据,如果它是存在的,否则得到一个空的数据集作为回报。该方法根据列的dtypes返回DataFrame的列的子集。
示例 1:
# 返回值s Two column of int64
df.select_dtypes(include = 'int64')
输出:
示例 2:
# 返回值s columns excluding int64
df.select_dtypes(exclude = 'int64')
输出 :
例子3 :
# Print an empty list as there is
# no column of bool type
df.select_dtypes(include = "bool")
输出 :