按dtype选择Pandas列

can*_*ner 32 python scipy pandas

我想知道在Pandas DataFrames中是否有一种优雅和简便的方式来按数据类型(dtype)选择列.即仅从DataFrame中选择int64列.

详细说明,有些东西

df.select_columns(dtype=float64)
Run Code Online (Sandbox Code Playgroud)

在此先感谢您的帮助

And*_*den 45

从0.14.1开始,有一种select_dtypes方法可以让你更优雅/更普遍地做到这一点.

In [11]: df = pd.DataFrame([[1, 2.2, 'three']], columns=['A', 'B', 'C'])

In [12]: df.select_dtypes(include=['int'])
Out[12]:
   A
0  1
Run Code Online (Sandbox Code Playgroud)

要选择所有数字类型,请使用numpy dtype numpy.number

In [13]: df.select_dtypes(include=[np.number])
Out[13]:
   A    B
0  1  2.2

In [14]: df.select_dtypes(exclude=[object])
Out[14]:
   A    B
0  1  2.2
Run Code Online (Sandbox Code Playgroud)


Dan*_*lan 34

df.loc[:, df.dtypes == np.float64]
Run Code Online (Sandbox Code Playgroud)


小智 13

df.select_dtypes(include=[np.float64])
Run Code Online (Sandbox Code Playgroud)


Max*_*axU 5

我想通过添加选择所有浮动 dtype或所有整数 dtype的选项来扩展现有答案:

演示:

np.random.seed(1234)

df = pd.DataFrame({
        'a':np.random.rand(3), 
        'b':np.random.rand(3).astype('float32'), 
        'c':np.random.randint(10,size=(3)).astype('int16'),
        'd':np.arange(3).astype('int32'), 
        'e':np.random.randint(10**7,size=(3)).astype('int64'),
        'f':np.random.choice([True, False], 3),
        'g':pd.date_range('2000-01-01', periods=3)
     })
Run Code Online (Sandbox Code Playgroud)

产量:

In [2]: df
Out[2]:
          a         b  c  d        e      f          g
0  0.191519  0.785359  6  0  7578569  False 2000-01-01
1  0.622109  0.779976  8  1  7981439   True 2000-01-02
2  0.437728  0.272593  0  2  2558462   True 2000-01-03

In [3]: df.dtypes
Out[3]:
a           float64
b           float32
c             int16
d             int32
e             int64
f              bool
g    datetime64[ns]
dtype: object
Run Code Online (Sandbox Code Playgroud)

选择所有浮动数字列:

In [4]: df.select_dtypes(include=['floating'])
Out[4]:
          a         b
0  0.191519  0.785359
1  0.622109  0.779976
2  0.437728  0.272593

In [5]: df.select_dtypes(include=['floating']).dtypes
Out[5]:
a    float64
b    float32
dtype: object
Run Code Online (Sandbox Code Playgroud)

选择所有整数列:

In [6]: df.select_dtypes(include=['integer'])
Out[6]:
   c  d        e
0  6  0  7578569
1  8  1  7981439
2  0  2  2558462

In [7]: df.select_dtypes(include=['integer']).dtypes
Out[7]:
c    int16
d    int32
e    int64
dtype: object
Run Code Online (Sandbox Code Playgroud)

选择所有数字列:

In [8]: df.select_dtypes(include=['number'])
Out[8]:
          a         b  c  d        e
0  0.191519  0.785359  6  0  7578569
1  0.622109  0.779976  8  1  7981439
2  0.437728  0.272593  0  2  2558462

In [9]: df.select_dtypes(include=['number']).dtypes
Out[9]:
a    float64
b    float32
c      int16
d      int32
e      int64
dtype: object
Run Code Online (Sandbox Code Playgroud)


Gur*_*bux 5

多个包含用于选择具有类型列表的列,例如 float64 和 int64

df_numeric = df.select_dtypes(include=[np.float64,np.int64])
Run Code Online (Sandbox Code Playgroud)