在Python中,我有一个包含多行和多列的数据集。如果一个column=X的值,我对它上面的行和右边的列的值感兴趣,所以加上值x的前一个位置的[1,1]。
解决这个问题的最好方法是什么?如果是cell =X,有没有一种动态的方法,我可以获得位置,然后添加X数量的行和列,“因为我对那个单元格的值感兴趣”?
发布于 2020-01-29 12:33:12
假设我们的数组定义为:
import numpy as np
arr = np.array([[9, 8, 4, 5, 2],
[0, 3, 5, 6, 7],
[6, 6, 2, 0, 6],
[2, 0, 2, 5, 8],
[2, 6, 9, 7, 9]])一种直接的解决方案是循环遍历感兴趣的列。
colIndex = 2
X = 2
rDelta = -1 #row change, up is negative!
cDelta = 1 #col change, right is positive
numberRows = np.shape(arr)[1]
output = []
#This loops through all the values in the specified column and looks for
#matches, if a match is found it is added to an output list
#Note that we only look at values that would result in valid output
# for example we will not look at the first row if
# we would need to index into the row above for the output
for i in range(max(-rDelta,0),min(numberRows,numberRows-rDelta)):
if(arr[i,colIndex]==X):
#replace this with your processing
output.append(arr[i+rDelta,colIndex+cDelta]) 运行这段代码后,我得到的输出如下
[6, 0]它们是第二列中2的上边和右边的值。
https://stackoverflow.com/questions/59960225
复制相似问题