python 如何使用cython循环数组?

8yoxcaq7  于 2023-01-04  发布在  Python
关注(0)|答案(1)|浏览(131)

我试着用不同的选项迭代数组。但是所有的选项都花费了大量的处理时间。我怎样才能在Cython中使用数组迭代?

#Assign the crop specific irrigated area of each array for each month according to the crop calander
#Maize
arr_5=maz_st_1
#repaeat it for every twelve month
arr5_re=np.repeat(arr_5, 12)
maz_itr=arr5_re.flatten()
maz_itr=arr5_re.tolist()
k=df_dist.Planting_month[5]
l=df_dist.Maturity_month[5]
for i in range (len(maz_itr)):
     for j in range(min(k,l), max(k,l)+1):
          for n in range (len(df_area.Maize)):
           # Assign the grid cell value for each growing month of maize
              df_area.loc[n,"Maize"]=maz_itr[i]

我的目标是为每种作物分配每个网格单元的种植面积。在本例中,我希望在生长季节条件下(即作物种植日期和成熟日期之间的月份)为每个网格单元分配玉米面积。

qlvxas9a

qlvxas9a1#

def axis_to_axeslist(axis, ndim): if axis is None: 
return [-1] * ndim else: if type(axis) is not tuple: 
axis = (axis,) axeslist = [1] * ndim for i in 
axis: axeslist[i] = -1 ax = 0 for i in range(ndim): 
if axeslist[i] != -1: axeslist[i] = ax 

ax += 1 return axeslist def sum_squares_py(arr, axis=None, out=None): axeslist = axis_to_axeslist(axis, arr.ndim) it = np.nditer([arr, out], flags=['reduce_ok', 'buffered', 'delay_bufalloc'], op_flags=[['readonly'], ['readwrite', 'allocate']], 

op_axes=[None, axeslist], op_dtypes=['float64', 'float64']) with it: it.operands[1][...] = 0 it.reset() for x, y in it: y[...] += x*x return it.operands[1] 
a = np.arange(6).reshape(2,3) sum_squares_py(a) array(55.) sum_squares_py(a, axis=-1) array([ 5., 50.])

相关问题