【问题标题】:Count number of distinct columns in a matrix [duplicate]计算矩阵中不同列的数量[重复]
【发布时间】:2013-12-30 01:31:37
【问题描述】:

我有一些简单的代码,我只想计算两个矩阵乘积中不同列的数量。代码是

import numpy as np
import itertools

n = 5
h = 2
M =  np.random.randint(2, size=(h,n))
F = np.matrix(list(itertools.product([0,1],repeat = 5))).transpose()
product = M*F
setofcols = set()
for column in product.T:
    setofcols.add(column)
print len(setofcols)

但是这给出了错误的答案,因为即使列相同,setofcols 的所有元素也不同。什么是正确的做法?

我将使用更大的 n 和 h 值来运行它,因此使用尽可能少的内存的解决方案会很棒。

【问题讨论】:

  • 你的意思是每列都包含独特的内容?
  • 使用setofcols.add(repr(column))答案是10
  • @alko 我将不得不更改我的代码以为此使用数组。我试过 F = np.array(list(itertools.product([0,1],repeat = 5))).transpose() 但后来我得到 TypeError: unhashable type: 'numpy.ndarray'
  • @marshall 为什么?您也可以在我为矩阵提供的线程中使用解决方案。或者如果您有疑问,请使用 np.array(F*M)

标签: python numpy


【解决方案1】:

您可以使用repr

import numpy as np
import itertools

n = 5
h = 2
M =  np.random.randint(2, size=(h,n))
F = np.matrix(list(itertools.product([0,1],repeat = 5))).transpose()
product = M*F
setofcols = set()
for column in product.T:
    setofcols.add(repr(column))
print len(setofcols)
print setofcols

您也可以这样做:

setofcols={tuple(e.A1) for e in product.T}

其中矩阵的A1 属性是一维基本数组,可用作tuple 的序列。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-21
    • 2020-02-24
    • 2021-01-01
    • 2020-01-28
    • 1970-01-01
    相关资源
    最近更新 更多