将固定数组作为常量填充numpy数组

时间:2016-08-01 11:25:53

标签: python arrays numpy

我有以下代码:

x = np.array([[1]])
print x
print np.lib.pad(x,(1,1),mode='constant',constant_values=[4,8])

输出:

[[1]]
[[4 4 8]
[4 1 8]
[4 8 8]]

问题是: 在常量值中,我想以新的填充为例:

print np.lib.pad(x,(1,1),mode='constant',constant_values = [1,2,3,4,5,6,7,8])

输出如:

[[1,2,3]
[8,1,4]
[7,6,5]]

2 个答案:

答案 0 :(得分:1)

这是Print two-dimensional array in spiral order的反向工程:

inner_array = np.array([3, 6, 7, 2])
outer_array = np.array([0, 23, 3, 5, 6, 8, 99, 73, 18, 42, 67, 88, 91, 12])

total_array = inner_array[::-1][np.newaxis]
i = 0
while True:
    s = total_array.shape[1]
    try:
        total_array = np.vstack([total_array, outer_array[i:i+s]])
    except ValueError:
        break
    try:
        total_array = np.rot90(total_array, -1)
    except ValueError:
        pass
    i += s
total_array = np.rot90(total_array, -1)
print(total_array)

答案 1 :(得分:0)

答案是不同的,因为它非常适合我的问题(Field Of View)。

def updatevalues(self,array,elementsCount): 
    counter =0
    R1 =Agent.GetCenterCoords(array.shape)[0]
    C1 = array.shape[1]-1
    coords = {'R1':R1,'R2':R1,'C1':C1,'C2':C1,'Phase':1}
    array[coords['R1'],coords['C1']] = True

    while counter<elementsCount:
        counter +=2
        self.Phases[coords['Phase']](array,coords)

def Phase1(self,array,coords):
    '''
    Phase 1.
    During this phase we start from the max column(C1,C2) and middle Row (R1,R2) 
    and start moving up and down till  
    minimum row (R1 ) , max Row (R2) then we move to phase 2
    '''
    coords['R1'] -=1
    coords['R2'] +=1
    array[coords['R1'],coords['C1']] = True
    array[coords['R2'],coords['C2']] = True
    if coords['R1']==0 or coords['R2'] == array.shape[0]-1:
        coords['Phase']=2

def Phase2(self,array,coords):
    '''
    Phase 2.
    During this phase we start from the max column (C1,C2) and Min,Max Rows (R1,R2) 
    and start changing (C1,C2 to minimum) till
    C1,C2 ==0 then we move to phase 3
    '''
    coords['C1'] -=1
    coords['C2'] -=1
    array[coords['R1'],coords['C1']] = True
    array[coords['R2'],coords['C2']] = True
    if coords['C1']==0 or coords['C2'] ==0:
        coords['Phase']=3

def Phase3(self,array,coords):
    '''
    Phase 3.
    During this phase we start from the minimum columns (C1,C2) and Min,Max Rows (R1,R2) 
    and start changing (R1,R2) toward center till R1==R2 then we break (all border got covered)
    '''
    coords['R1'] +=1
    coords['R2'] -=1
    array[coords['R1'],coords['C1']] = True
    array[coords['R2'],coords['C2']] = True
    if coords['R1']==coords['R2']:
        coords['Phase']=4

@staticmethod
def GetCenterCoords(shape):
    return (shape[0]-1)/2 , (shape[1]-1)/2

解决方案取决于我们想要在边界上从最大行,中间列到右边开始更改多少个值,然后同时开始向两个方向移动。 很抱歉这个复杂的解决方案,但正如我告诉你@Ophir它是我的问题的相当自定义的解决方案。 (当我提出问题时,我使用了一个非常通用的论坛来简化它。) 希望有一天能帮到别人。