Is there a MATLAB accumarray equivalent in numpy?

后端 未结 7 1675
时光说笑
时光说笑 2021-01-01 18:06

I\'m looking for a fast solution to MATLAB\'s accumarray in numpy. The accumarray accumulates the elements of an array which belong to the same index. An exampl

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-01 18:58

    You can do this with pandas DataFrame in one line.

    In [159]: df = pd.DataFrame({"y":np.arange(1,11),"x":[0,1,0,0,0,1,1,2,2,1]})
    
    In [160]: df
    Out[160]: 
       x   y
    0  0   1
    1  1   2
    2  0   3
    3  0   4
    4  0   5
    5  1   6
    6  1   7
    7  2   8
    8  2   9
    9  1  10
    
    In [161]: pd.pivot_table(df,values='y',index='x',aggfunc=sum)
    Out[161]: 
        y
    x    
    0  13
    1  25
    2  17
    

    You can tell the pivot_table to use specific columns as indices and values, and get a new DataFrame object. When you specify the aggregation function as the sum the results will be identical to Matlab's accumarray.

提交回复
热议问题