题目:选择特定数据类型(Python)
现在有一组人员信息的DataFrame ,如下面所示:
姓名 | 年龄 | 身高 | 体重 | 工资 |
---|---|---|---|---|
John Doe | 32 | 170.2 | 70.1 | 56000 |
Jane Doe | 28 | 165.1 | 60.5 | 62000 |
Mike Roe | 45 | 175.3 | 85.6 | 75000 |
Sarah Poe | 37 | 160.6 | 58.2 | 69000 |
假设年龄、身高和体重的数据类型分别是整数、浮点数和浮点数,而工资的数据类型是整数。
要求:
- 仅选择数据类型为整数和浮点数的列;
- 排除数据类型为字符串的列。
答案
解题思路
这个问题的关键在于如何使用 Pandas 的 select_dtypes()
函数来选择或排除特定数据类型的列。我们可以使用 include
参数来包含特定的数据类型,使用 exclude
参数来排除特定的数据类型。
答案代码
下面是如何实现这一操作的代码示例:
import pandas as pd
data = {
'Name': ['John Doe', 'Jane Doe', 'Mike Roe', 'Sarah Poe'],
'Age': [32, 28, 45, 37],
'Height': [170.2, 165.1, 175.3, 160.6],
'Weight': [70.1, 60.5, 85.6, 58.2],
'Salary': [56000, 62000, 75000, 69000]
}
df = pd.DataFrame(data)
# 仅选择数据类型为整数和浮点数的列
numerical_df = df.select_dtypes(include=['int', 'float'])
print("仅包含整数和浮点数的列:\n", numerical_df)
# 排除数据类型为字符串的列
non_string_df = df.select_dtypes(exclude=['object'])
print("排除字符串类型的列:\n", non_string_df)
select_dtypes(include=['int', 'float'])
: 包含整数和浮点数数据类型的列。select_dtypes(exclude=['object'])
: 排除字符串数据类型的列。include
和exclude
参数可以是字符串或列表,帮助灵活选择或排除不同的数据类型。
更多详细答案可关注公众号查阅。