Python 如何按类型选择数据帧中的列

Python 如何按类型选择数据帧中的列,python,pandas,Python,Pandas,假设我有一个不同类型的数据帧。设为float、string和int列 A B C 1 car 4.3 302 2 Lena -1.2 4 3 I 9.1 18 如何获取类型为“float”的列 而不是直接引用列名。使用: 输出: B 1 4.3 2 -1.2 3 9.1 使用: 输出: B 1 4.3 2 -1.2 3 9.1 您可以尝试: df.select_dtypes(float) 或 您可以

假设我有一个不同类型的数据帧。设为float、string和int列

  A     B      C

1 car   4.3    302

2 Lena  -1.2   4

3 I     9.1    18  
如何获取类型为“float”的列

而不是直接引用列名。

使用:

输出:

     B
1  4.3
2 -1.2
3  9.1
使用:

输出:

     B
1  4.3
2 -1.2
3  9.1
您可以尝试:

df.select_dtypes(float)

您可以尝试:

df.select_dtypes(float)


您可以为此使用列表理解:

下面是一个示例数据帧:

import pandas as pd

df = pd.DataFrame({'one' : pd.Series([10, 0, 10, 9], index=['a', 'b', 'c', 'd']), //
  'two' : pd.Series([0, 0, 10., 4.6], index=['a', 'b', 'c', 'd']), //
  'three' : pd.Series(['aaa', 'abc', 'def', 'fff'], index=['a', 'b', 'c', 'd'])})

print(df)
"""
   one   two  three
a   10   0.0      5
b    0   0.0     -1
c   10  10.0      7
d    9   4.6     -1
"""
我的列类型是什么

for col in df.columns:
        print('col : ',col, ' , datatype: ',df[col].dtype)
"""
col:  one  , datatype:  int64
col:  two  , datatype:  float64
col:  three  , datatype:  object
"""
返回“float”类型的列

print(df[[col for col in df.columns if df[col].dtype == 'float']])
"""
    two
a   0.0
b   0.0
c  10.0
d   4.6
"""
返回多个列类型(float和int64)


您可以为此使用列表理解:

下面是一个示例数据帧:

import pandas as pd

df = pd.DataFrame({'one' : pd.Series([10, 0, 10, 9], index=['a', 'b', 'c', 'd']), //
  'two' : pd.Series([0, 0, 10., 4.6], index=['a', 'b', 'c', 'd']), //
  'three' : pd.Series(['aaa', 'abc', 'def', 'fff'], index=['a', 'b', 'c', 'd'])})

print(df)
"""
   one   two  three
a   10   0.0      5
b    0   0.0     -1
c   10  10.0      7
d    9   4.6     -1
"""
我的列类型是什么

for col in df.columns:
        print('col : ',col, ' , datatype: ',df[col].dtype)
"""
col:  one  , datatype:  int64
col:  two  , datatype:  float64
col:  three  , datatype:  object
"""
返回“float”类型的列

print(df[[col for col in df.columns if df[col].dtype == 'float']])
"""
    two
a   0.0
b   0.0
c  10.0
d   4.6
"""
返回多个列类型(float和int64)


df.选择数据类型
,搜索
如何按类型选择数据框中的列
,Google给出第一个结果…
df.选择数据类型
,使用Google搜索如何按类型选择数据框中的列作为第一个结果。。。