简体   繁体   中英

Sum 2d numpy array by element

I need to sum up a numpy array by index 1, AKA, the region the Species is in. The original data is in a .csv file, but I converted that to a numpy array. All that's left is figuring out how to sort and sum by what I need. Would a simple if statement be better than a numpy array function?

The array looks kinda like this (Linked below):

#(Species) (Region located) (# of individuals) <-- For your convenience

[['Purple Puffin' '1' '1']
['Wisteria Wombat' '3' '4']
['Pumpkin Pomeranian' '1' '3']
['Wisteria Wombat' '2' '3']
['Burgundy Bichon Frise' '2' '1']
['Purple Puffin' '1' '4']
['Wisteria Wombat' '2' '2']
['Pumpkin Pomeranian' '1' '2']]

But the full array has more data and I can link that in.

I need to sum up the "# of individuals" in each "Region". The final output should look like this in a numpy array:

['Burgundy Bichon Frise' '1' '#']
['Pumpkin Pomeranian' '1' '#']
['Purple Puffin' '1' '#']
['Wisteria Wombat' '1' '#']

['Burgundy Bichon Frise' '2' '#']
['Pumpkin Pomeranian' '2' '#']
['Purple Puffin' '2' '#']
['Wisteria Wombat' '2' '#']

['Burgundy Bichon Frise' '3' '#']
['Pumpkin Pomeranian' '3' '#']
['Purple Puffin' '3' '#']
['Wisteria Wombat' '3' '#']

Each region is separated into species and each species population is summed together. This needs to end up in a numpy array.

EDIT I got the array sorted by the species and region. Now I just need to know how to add up the "# of individuals" in each region by each species.

Link to full numpy data set

You can use np.unique and np.bincount :

>>> inp
array([['Purple Puffin', '1', '1'],
       ['Wisteria Wombat', '3', '4'],
       ['Pumpkin Pomeranian', '1', '3'],
       ['Wisteria Wombat', '2', '3'],
       ['Burgundy Bichon Frise', '2', '1'],
       ['Purple Puffin', '1', '4'],
       ['Wisteria Wombat', '2', '2'],
       ['Pumpkin Pomeranian', '1', '2']], dtype='<U21')
>>> unq, inv = np.unique(inp[:, 1::-1], axis=0, return_inverse=True)
>>> cnt = np.bincount(inv, inp[:, 2].astype(int)).astype(int)
>>> res = np.c_[unq[:, ::-1], cnt]
>>> res
array([['Pumpkin Pomeranian', '1', '5'],
       ['Purple Puffin', '1', '5'],
       ['Burgundy Bichon Frise', '2', '1'],
       ['Wisteria Wombat', '2', '5'],
       ['Wisteria Wombat', '3', '4']], dtype='<U21')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM