如何检测numpy矩阵中的列类型?

时间:2014-08-11 08:53:03

标签: python numpy

我有一个训练数据集,我将其转换为numpy矩阵以训练分类器。但在此之前,我需要对矩阵进行一些预处理。在矩阵中,每行代表一个实例/记录,每列都是一个属性。对于每种类型的属性,我需要进行特定的预处理,即实值属性/列具有与仅具有二进制值的列不同的预处理。

这些是我想要做的预处理步骤:

对于只有实际值的列:

  • 制作10个箱/间隔(0.0,0.1),(0.1,0.2),(0.2,0.3),(0.3,0.4),......,(0.9,1.0)。然后找到属于第一个bin,第二个bin等的行的索引

对于只包含二进制值的列:

  • 查找所有以零作为值的行的索引,以及将1作为值的所有行的索引

我的问题

1-是否有一种有效/好的方法来自动检测列的类型?我需要这个,所以我可以自动化过程,不必手动检查矩阵,然后进行预处理。

2-假设我知道第0列只有实数值,那么我知道如何得到像这样的行的索引:np.nonzero(X[:,0]>0.1),但这不是我需要的,因为它缺少第二个条件,例如:np.nonzero(X[:,0]<0 and X[:,0]<0.2)当然这不起作用,所以我不知道在这里加入第二个条件。

EDIT1:

这就是我解决第二个问题的方法:

X = np.random.randn(8,3)

bins = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]
bins = np.array(bins)

col = X[:,0] #here I detect that the first column is real-valued.

binplace = np.digitize(col, bins) #each element in binplace is the index of the bin that this element falls into.

for bin in xrange(bins.size):
    elements_inds = np.where(binplace==bin)[0]

EDIT2:

这是一个小的脏黑客来尝试检测列的类型:

#To detect which cols are which type
n_rows = X.shape[0]

#check if col0 is binary or not

v=(X[:,0] == 1)

num_ones = np.where(v)[0].size

v=(X[:,0] == 0)

num_zeros = np.where(v)[0].size

total_size = num_ones + num_zeros


if n_rows == total_size:
    print 'this is a binary column'
else:
    print 'this is a real-valued column'

1 个答案:

答案 0 :(得分:0)

首先,让我们做一些示例数据:

x = np.random.randn(5, 5)
# we threshold columns 1 and 3 so that they're either 0 or 1
x[:, [1, 3]] = x[:, [1, 3]] > 0

print x
# [[ 1.65585901  1.         -0.05846647  0.          0.19013289]
#  [-0.60492332  0.         -0.23341666  1.         -0.66814078]
#  [-0.60287221  0.         -0.99057634  0.          0.45945837]
#  [ 0.33393323  0.          0.23511501  1.          0.62303913]
#  [-0.66428594  1.         -0.35667229  0.          1.07982347]]

现在你基本上想找到所有条目都非常接近0或非常接近1的列。

你做这样的事情:

bool_cols = np.all(np.logical_or(np.isclose(x, 0), np.isclose(x, 1)), axis=0)
print bool_cols
# [False  True False  True False]

解压该行:

您可以直接使用布尔索引集,例如x[:, bool_cols],或者您可以使用np.where返回布尔列的索引。

如果您的某些列是整数值,则可以使用%(modulo)运算符来查找除以1的余数非常小的列,例如:

int_cols = np.all(np.isclose(x % 1, 0), axis=0)

但是,这些索引还包括任何布尔列。