You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

numpy recarray无select_dtypes属性,如何筛选指定数据类型列?

Numpy Recarray筛选特定数据类型列的等效方法

你可以通过以下两种方式实现类似select_dtypes的功能,筛选numpy recarray中特定数据类型的列:

方法一:直接基于numpy dtype筛选

numpy recarray的dtype属性包含了各列的数据类型信息,我们可以遍历列名并判断其数据类型,再提取目标列:

import numpy as np
# 构建示例recarray
a = np.array([1,2,3,4], dtype=int)
b = np.array([6,6,6,6], dtype=int)
c = np.array(['p', 'q', 'r', 's'], dtype=object)
d = np.array(['a', 'b', 'c', 'd'], dtype=object)
X = np.rec.fromarrays([a, b, c, d], names=['a', 'b', 'c', 'd'])

# 筛选object类型的列
object_cols = [name for name in X.dtype.names if X.dtype[name].kind == 'O']
X_object = X[object_cols]
print(X_object)

输出结果:

rec.array([('p', 'a'), ('q', 'b'), ('r', 'c'), ('s', 'd')],
          dtype=[('c', 'O'), ('d', 'O')])

其中X.dtype[name].kind返回数据类型的简写标识:'O'代表object类型,'i'代表整数类型,'f'代表浮点数类型等,可根据需求调整判断条件。

方法二:借助pandas中转

如果习惯使用pandas的select_dtypes,可以先将recarray转为DataFrame,筛选后再转回recarray:

import pandas as pd
# 转为DataFrame
df = pd.DataFrame(X)
# 筛选object类型列
df_object = df.select_dtypes(include='object')
# 转回recarray
X_object = df_object.to_records(index=False)
print(X_object)

输出结果和方法一一致。

注意:如果recarray包含复杂数据类型,转DataFrame时可能需要额外处理,但常规场景下该方法适用。

内容的提问来源于stack exchange,提问作者user3046211

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 06:50:52