【问题标题】:How too loop arrays using cython?如何使用cython循环数组?
【发布时间】:2023-01-03 15:37:49
【问题描述】:

我试图使用几个选项来迭代数组。然而,所有这些都花费了大量的处理时间。如何在 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 df_area.Month:
        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]

我的目标是为每种作物的每个网格单元分配种植面积。在这种情况下,我想在生长季节条件下(当月份在作物的种植和成熟日期之间时)为每个网格单元分配玉米面积。

【问题讨论】:

    标签: python arrays cython numpy-ndarray numba


    【解决方案1】:
    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.])
    

    【讨论】:

      猜你喜欢
      • 2022-06-30
      • 2015-08-10
      • 2019-06-02
      • 2020-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-18
      • 1970-01-01
      相关资源
      最近更新 更多