按dtype选择Pandas列

时间:2014-01-21 23:59:08

标签: python pandas scipy

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

详细说明,

df.select_columns(dtype=float64)

提前感谢您的帮助

9 个答案:

答案 0 :(得分:34)

从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
  

要选择所有数字类型,请使用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

答案 1 :(得分:31)

df.loc[:, df.dtypes == np.float64]

答案 2 :(得分:11)

df.select_dtypes(include=[np.float64])

答案 3 :(得分:3)

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

演示:

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)
     })

的产率:

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

选择所有浮点数列:

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

选择所有整数列:

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

选择所有数字列:

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

答案 4 :(得分:2)

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

df_numeric = df.select_dtypes(include=[np.float64,np.int64])

答案 5 :(得分:2)

如果要选择int64列然后更新“就地”,则可以使用:

int64_cols = [col for col in df.columns if is_int64_dtype(df[col].dtype)]
df[int64_cols]

例如,请注意,我将df中的所有int64列更新为以下零:

In [1]:

    import pandas as pd
    from pandas.api.types import is_int64_dtype

    df = pd.DataFrame({'a': [1, 2] * 3,
                       'b': [True, False] * 3,
                       'c': [1.0, 2.0] * 3,
                       'd': ['red','blue'] * 3,
                       'e': pd.Series(['red','blue'] * 3, dtype="category"),
                       'f': pd.Series([1, 2] * 3, dtype="int64")})

    int64_cols = [col for col in df.columns if is_int64_dtype(df[col].dtype)] 
    print('int64 Cols: ',int64_cols)

    print(df[int64_cols])

    df[int64_cols] = 0

    print(df[int64_cols]) 

Out [1]:

    int64 Cols:  ['a', 'f']

           a  f
        0  1  1
        1  2  2
        2  1  1
        3  2  2
        4  1  1
        5  2  2
           a  f
        0  0  0
        1  0  0
        2  0  0
        3  0  0
        4  0  0
        5  0  0

仅出于完整性考虑:

df.loc()和df.select_dtypes()将提供数据帧中切片的副本。这意味着,如果您尝试从df.select_dtypes()更新值,则将获得SettingWithCopyWarning,并且不会对df进行任何更新。

例如,请注意,当我尝试使用.loc()或.select_dtypes()选择列来更新df时,什么也没发生:

In [2]:

    df = pd.DataFrame({'a': [1, 2] * 3,
                       'b': [True, False] * 3,
                       'c': [1.0, 2.0] * 3,
                       'd': ['red','blue'] * 3,
                       'e': pd.Series(['red','blue'] * 3, dtype="category"),
                       'f': pd.Series([1, 2] * 3, dtype="int64")})

    df_bool = df.select_dtypes(include='bool')
    df_bool.b[0] = False

    print(df_bool.b[0])
    print(df.b[0])

    df.loc[:, df.dtypes == np.int64].a[0]=7
    print(df.a[0])

Out [2]:

    False
    True
    1

答案 6 :(得分:1)

select_dtypes(include = [np.int])

答案 7 :(得分:0)

(可选)如果您不想在此过程中创建数据框的子集,则可以直接遍历列数据类型。

我还没有对下面的代码进行基准测试,假设如果处理非常大的数据集,它将更快。

[col for col in df.columns.tolist() if df[col].dtype not in ['object','<M8[ns]']] 

答案 8 :(得分:0)

您可以使用:

for i in x.columns[x.dtypes == 'object']:   print(i)

如果您只想仅显示特定数据框的列名,而不是切片数据框。不知道是否有任何这样的功能退出python。

PS:将object替换为所需的数据类型。

相关问题