[SciPy-User] Accumulation sum using indirect indexes
Wes McKinney
wesmckinn at gmail.com
Tue Jan 31 16:32:59 EST 2012
On Tue, Jan 31, 2012 at 3:34 PM, Alexander Kalinin
<alec.kalinin at gmail.com> wrote:
> Hello!
>
> I use SciPy in computer graphics applications. My task is to calculate
> vertex normals by averaging faces normals. In other words I want to
> accumulate vectors with the same ids. For example,
>
> ids = numpy.array([0, 1, 1, 2])
> n = numpy.array([ [0.1, 0.1, 0.1], [0.1, 0.1, 0.1], [0.1, 0.1, 0.1], [0.1,
> 0.1 0.1] ])
>
> I need result:
> nv = ([ [0.1, 0.1, 0.1], [0.2, 0.2, 0.2], [0.1, 0.1, 0.1]])
>
> The most simple code:
> nv[ids] += n
> does not work, I know about this. For 1D arrays I use numpy.bincount(...)
> function. But this function does not work for 2D arrays.
>
> So, my question. What is the best way calculate accumulation sum for 2D
> arrays using indirect indexes?
>
> Sincerely,
> Alexander
>
> _______________________________________________
> SciPy-User mailing list
> SciPy-User at scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user
>
It's long been on the pandas (http://pandas.sf.net) feature queue to
expose the GroupBy engine to NumPy arrays generally:
https://github.com/wesm/pandas/issues/123
for this you could certainly use a pandas.DataFrame:
In [19]: n
Out[19]:
array([[ 0.1, 0.1, 0.1],
[ 0.1, 0.1, 0.1],
[ 0.1, 0.1, 0.1],
[ 0.1, 0.1, 0.1]])
In [20]: df = DataFrame(n)
In [21]: df.groupby(ids).sum()
Out[21]:
0 1 2
key_0
0 0.1 0.1 0.1
1 0.2 0.2 0.2
2 0.1 0.1 0.1
if you want the ndarray back you can just get the .values attribute:
In [22]: df.groupby(ids).sum().values
Out[22]:
array([[ 0.1, 0.1, 0.1],
[ 0.2, 0.2, 0.2],
[ 0.1, 0.1, 0.1]])
hope this helps,
Wes
More information about the SciPy-User
mailing list