如何在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的数据类型为float64,Col2的数据类型为object,Col3存储的是整数(int64)类型数据。
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
示例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。
广告