【问题标题】:Join two python arrays via index通过索引加入两个 python 数组
【发布时间】:2016-01-04 18:48:04
【问题描述】:

我在 Python 中遇到了问题。我正在从 dict 条目创建两个 numpy 数组。我想以这样的特定方式加入这两个 numpy 数组:

# create array with classes
probVec = filePickle['classID']
a = np.empty([0, 1])

for x in np.nditer(probVec):
    a = np.append(a,x)

timeVec = filePickle['start']
timeVec = np.asarray(timeVec)
b = np.empty([0, 1])

for x in np.nditer(timeVec):
    b = np.append(b,x)

# create input-vectors for clustering
c = np.vstack((b,a)).transpose()

现在,如果我想以更具体的方式加入它们,例如仅将数组“probVec”的特定项与数组“timeVec”的相应条目加入它们,如下所示:

for x in np.nditer(probVec):
    if x == 3.0:
        a = np.append(a,x)

for x in np.nditer(timeVec):
    b = append with x values that have the same indices as the ones appended in the first loop

因为两个数组都包含彼此对应的值,所以它们的长度相同。所以我的目标是这样的:

probVec = [2.0, 1.0, 3.0, 3.0, 4.0, 3.0...]

timeVec = [t1, t2, t3, t4, t5, t6...]

c = [[3.0 t3]
     [3.0 t4]
     [3.0 t6]
         .
         .
         .
     ]

我只是不知道实现这一点的最佳方法是什么。

【问题讨论】:

    标签: python-3.x numpy multidimensional-array


    【解决方案1】:

    在数组上使用比较运算符,例如a == 3.0,您会得到一个布尔数组,可用于索引,选择条件为真的行。

    In [87]: a = np.random.randint(low=1, high=4, size=10)   # example data
    
    In [88]: a
    Out[88]: array([3, 1, 3, 1, 1, 3, 2, 2, 2, 2])
    
    In [89]: b = np.arange(10)
    
    In [90]: c = np.column_stack((a, b))
    
    In [91]: c[a == 3]
    Out[91]: 
    array([[3, 0],
           [3, 2],
           [3, 5]])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-02
      • 2018-07-14
      • 1970-01-01
      • 2011-05-23
      • 1970-01-01
      • 1970-01-01
      • 2014-10-01
      • 2015-02-11
      相关资源
      最近更新 更多