如何在Pandas中只选择数值型的列(附实例)

739 阅读2分钟

你可以使用下面的基本语法在pandas DataFrame中只选择数字列:

import pandas as pd
import numpy as np

df.select_dtypes(include=np.number)

下面的例子展示了如何在实践中使用这个函数。

例子:在Pandas中只选择数字列

假设我们有如下的pandas DataFrame,其中包含了各种篮球运动员的信息:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'team': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
                   'points': [18, 22, 19, 14, 14, 11, 20, 28],
                   'assists': [5, 7, 7, 9, 12, 9, 9, 4],
                   'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]})

#view DataFrame
print(df)

  team  points  assists  rebounds
0    A      18        5        11
1    B      22        7         8
2    C      19        7        10
3    D      14        9         6
4    E      14       12         6
5    F      11        9         5
6    G      20        9         9
7    H      28        4        12

我们可以使用下面的语法来只选择DataFrame中的数字列:

import numpy as np

#select only the numeric columns in the DataFrame
df.select_dtypes(include=np.number)

        points	assists	rebounds
0	18	5	11
1	22	7	8
2	19	7	10
3	14	9	6
4	14	12	6
5	11	9	5
6	20	9	9
7	28	4	12

注意,只有三个数字列被选中--得分助攻篮板

我们可以通过使用**dtypes()**函数显示DataFrame中每个变量的数据类型来验证这些列是数值列:

#display data type of each variable in DataFrame
df.dtypes

team        object
points       int64
assists      int64
rebounds     int64
dtype: object

从输出中我们可以看到,球队是一个对象(即字符串),而得分助攻篮板都是数字。

请注意,我们也可以使用下面的代码来获得DataFrame中数字列的列表:

#display list of numeric variables in DataFrame
df.select_dtypes(include=np.number).columns.tolist()

['points', 'assists', 'rebounds']

这允许我们快速查看DataFrame中数字变量的名称,而不用看到它们的实际值。

其他资源

下面的教程解释了如何在pandas中执行其他常见任务:

如何在Pandas中按名称选择列
如何在Pandas中按索引选择列
如何在Pandas中选择包含特定字符串的列