我想创建一个具有格式的数组,值来自另一个数组。我的输入数组由三列组成。我想创建一个数组,如果第二列相等,则在第一行中包含来自第三列的所有值。因此在本例中,第二列中的前三个值是相等的,所以在新数组中,我想要新数组中每行的第三个值。
a =
[[1, 1, 4],
[2, 1, 6],
[3, 1, 7],
[4, 2, 0],
[5, 2, 7],
[6, 3, 1]]结果:
b =
[[4, 6 , 7],
[0, 7],
[1]]我试过了:
c = []
x = 1
for row in a:
if row[0] == x
c.extend[row[2]]
else:
x = x + 1
c.append(row[2])但是结果是所有第三个值的列表
发布于 2017-08-16 22:44:45
a = np.asarray(a)
c = []
for i in range(a[-1,1]): #a[-1,1] is the maximum that will occur
save = a[a[:,1]==i] # take all the ones that have i in the second entry
c.append(save[:,2]) # of those add the last entry重要的是,为此将a转换为np.array。
发布于 2017-08-16 22:48:47
下面的方法对我来说很有效:
import numpy as np
c = [[]]
x = 1
for row in a:
if row[1] == x:
c[-1].append(row[2])
else:
x = x + 1
c.append([row[2]])
c = np.asarray(c)发布于 2017-08-16 22:49:15
如果对第二列进行了排序,则可以使用np.diff找出值发生变化的索引,然后对其进行拆分:
np.split(a[:,2], np.flatnonzero(np.diff(a[:,1]) != 0)+1)
# [array([4, 6, 7]), array([0, 7]), array([1])]https://stackoverflow.com/questions/45716569
复制相似问题