如果数组在100之后出现,我想向数组添加值。如果包含100的列不是最后一列,则该工作正常(因为该行中的下一列值将附加到数组中) )。但是如果在最后一列中出现100值,则会发生IndexError,因为没有lastcol + 1值。
col1 col2 col3
nan 100 60
100 95 98
nan nan 100
现在:
values = [60,95,IndexError];
理想:
values = [60,95,100];
我的代码:
x1 = np.where(#table == 100.0)[0]; x2 = np.where(#table == 100.0)[1]
# np.where returns a tuple containing the (x,y) locations of
the 100 values in the table. e.g. [(0,1,2),(1,0,2)] for the
table in the above example.
for i,j in zip(x1,x2):
values.append(out[i][j+1]);
# Above attempts to add values
修改
col1 col2 col3 col4
nan 100 60 50
100 95 98 70
nan nan 100 80
nan nan nan 100
nan nan 100 100
所需:在行中出现100后获取值并将其附加到“values”数组。另请注意,在出现100个值之前,每行中都会出现nan
。
values = [60,95,80,100,100];
上述值出现在100之后的每一行(顺序很重要)。
答案 0 :(得分:1)
我不确定你的期望是什么,因为我不明白你如何得到values = [60,95,80,100,100];
但我猜你接近解决方案
规则:我们想要在第一次出现100之后的第一个值,如果第一个值100是最后一个值,那么接受它。
In [1]: A
Out[1]:
array([[ nan, 100., 60., 50.],
[ 100., 95., 98., 70.],
[ nan, nan, 100., 80.],
[ nan, nan, nan, 100.],
[ nan, nan, 100., 100.],
[ 100., 4., 100., 5.]])
In [2]: B = np.where(A==100)
A是2D:
然后:
In [3]: value = []
In [4]: for j in set(B[0]): # set returns unique values in array B[0]
idx = A[j].tolist().index(100) # I get the index of the first occurrence of 100 in line j of matrix A (list.index(value,[start,[stop]]) gives position of first occurrence from start to stop in list )
if idx+1 >= len(A[j]): # if it's last column ...
value.append(A[(j,idx)]) # ... add 100
else:
value.append(A[(j,idx+1)]) # if not, add value after 100
In [5]: value
Out[5]: [60.0, 95.0, 80.0, 100.0, 100.0, 4.0]
如果您的预期值为[ 60., 95., 80., 100., 100., 100.]
(在100之后取第一个值,或者如果100是最后一个则取100)
然后:
In [1]: A
Out[1]:
array([[ nan, 100., 60., 50.],
[ 100., 95., 98., 70.],
[ nan, nan, 100., 80.],
[ nan, nan, nan, 100.],
[ nan, nan, 100., 100.]])
In [2]: B = np.where(A==100)
In [3]: A[(B[0],[b+1 if b+1<len(A[0]) else b for b in B[1]])]
Out[3]: array([ 60., 95., 80., 100., 100., 100.])
如果您的预期值为[ 60., 95., 80., 100.]
,(在100之后取第一个值,如果100是最后一个不带什么),那么:
value = []
for i,j in zip(B[0],B[1]):
if j+1<len(A[0]):
value.append(A[i,j+1])
值现在是[60.0, 95.0, 80.0, 100.0]
如果你不明白,请告诉我。