【问题标题】:Python, Numpy: all UNIQUE combinations of a numpy.array() vectorPython,Numpy:numpy.array() 向量的所有唯一组合
【发布时间】:2015-11-09 15:26:46
【问题描述】:

我想获得 numpy.array 向量(或 pandas.Series)的所有 独特 组合。我使用了 itertools.combinations,但它非常慢。对于一个大小为 (1000,) 的数组,它需要很多小时。这是我使用 itertools 的代码(实际上我使用了组合差异):

def a(array):
    temp = pd.Series([])
    for i in itertools.combinations(array, 2):
        temp = temp.append(pd.Series(np.abs(i[0]-i[1])))
    temp.index=range(len(temp))
    return temp

如你所见,没有重复!! sklearn.utils.extmath.cartesian 真的又快又好,但它提供了我不想要的重复!我需要在不使用 itertools 的情况下重写上述函数的帮助,并且对于大型向量需要更快的速度。

【问题讨论】:

  • 这就是你想要的:stackoverflow.com/questions/1208118/… 如果是这样,我将作为副本关闭
  • 否,因为它不提供独特的组合! itertools 本身很慢!
  • 确保数组不能启动并屏蔽掉相等的值(对于它们自己/可能将它们作为特殊情况添加回来)?
  • 如果你的意思是向量数组,它是唯一的,因为它的元素是随机的 float64 数字。其实我不明白你的建议!
  • 另一个可能的解决方案是stackoverflow.com/questions/11144513/…

标签: numpy pandas combinations


【解决方案1】:

您可以使用二元运算(此处为减法,如您的示例)获取在笛卡尔积上形成的矩阵的上三角部分:

import numpy as np
n = 3
a = np.random.randn(n)
print(a)
print(a - a[:, np.newaxis])
print((a - a[:, np.newaxis])[np.triu_indices(n, 1)])

给予

[ 0.04248369 -0.80162228 -0.44504522]
[[ 0.         -0.84410597 -0.48752891]
 [ 0.84410597  0.          0.35657707]
 [ 0.48752891 -0.35657707  0.        ]]
[-0.84410597 -0.48752891  0.35657707]

n=1000(输出通过管道传输到/dev/null),运行时间为 0.131 秒 在我相对普通的笔记本电脑上。

【讨论】:

    【解决方案2】:

    对于随机整数数组:

        import numpy as np
        import pandas as pd
        import itertools as it
        b=np.random.randint(0,8,((6,)))
        #array([7, 0, 6, 7, 1, 5])
        pd.Series(list(it.combinations(np.unique(b),2)))
    

    给予

        0    (0, 1)
        1    (0, 5)
        2    (0, 6)
        3    (0, 7)
        4    (1, 5)
        5    (1, 6)
        6    (1, 7)
        7    (5, 6)
        8    (5, 7)
        9    (6, 7)
        dtype: object
    

    【讨论】:

    • 好又快。但是组合的顺序发生了变化。根据你的随机数组,我想要这个顺序的东西: (7,0) (7,6) (7,1) (7,7) (7,5) (0,6) (0,7) 等等.所以最好删除 np.unique()。谢谢你的帮助:)
    • 假设 pd = pandas,它是什么?缺少导入?
    • import itertools as it 丢失。
    • @dk-na 好点,更新
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 2012-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多