在Pandas数据框架中选择具有特定数据类型的列

  • Post category:Python

在 Pandas 数据框架中,我们可以选择具有特定数据类型的列,通过以下步骤实现:

1.使用 dtypes 属性查看每个列的数据类型。

import pandas as pd

df = pd.read_csv('example.csv')
print(df.dtypes)

2.使用 select_dtypes 方法可选择指定数据类型的列来创建一个新的数据框架。

df1 = df.select_dtypes(include=['int'])
print(df1)

在上面的例子中,使用 include=['int'] 来选择整数类型的列。也可以使用 exclude 参数来排除特定类型的列。

以下是一个完整的例子:

import pandas as pd

# 创建示例数据框架
data = {'Name': ['John', 'Sara', 'Sam', 'Kate', 'Mike'], 
        'Age': [45, 37, 22, 28, 33], 
        'Salary': [35000, 50000, 45000, 55000, 60000],
        'Birthdate': ['1995-03-10', '1990-12-15', '2000-05-22', '1996-08-30', '1988-11-05']}
df = pd.DataFrame(data)

# 查看每个列的数据类型
print(df.dtypes)

# 选择整数类型的列创建新的数据框架
df1 = df.select_dtypes(include=['int'])
print(df1)

# 选择日期列创建新的数据框架
df2 = df.select_dtypes(include=['datetime'])
print(df2)

输出结果为:

Name         object
Age           int64
Salary        int64
Birthdate    object
dtype: object
   Age  Salary
0   45   35000
1   37   50000
2   22   45000
3   28   55000
4   33   60000
   Birthdate
0 1995-03-10
1 1990-12-15
2 2000-05-22
3 1996-08-30
4 1988-11-05

在此示例中,我们首先创建了一个包含姓名、年龄、薪水和生日的示例数据框架。然后,我们使用 dtypes 属性查看每个列的数据类型,并选择整数类型的列和日期类型的列创建了两个新的数据框架。