Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy array mapping and take average

Tags:

python

numpy

I have three arrays

import numpy as np
value = np.array ([1, 3, 3, 5, 5, 7, 3])
index = np.array ([1, 1, 3, 3, 6, 6, 6])
data  = np.array ([1, 2, 3, 4, 5, 6])

Arrays "index" & "value" have same size and I want to group the items in "value" by taking average. For example: For the first two items [1, 3, ... in "value", have the same key 1 in "index", so for the final array the value is the mean of the 1st & 2rd items in value : (1 + 3 )/2 which is equal 2

The final array is:

[2, nan, 4, nan, nan, 5]

first value is the average of 1st and 2nd of "value"
second value is nan because there is not any key in "index" (no "2" in array index)
third value is the average of 3rd and 4th of "value" ...

Thanks for your help!!!

Regards, Roy

like image 782
Roy Avatar asked Nov 19 '25 22:11

Roy


1 Answers

>>> [value[index==i].mean() for i in data]
[2.0, nan, 4.0, nan, nan, 5.0]
like image 175
Steve Tjoa Avatar answered Nov 21 '25 13:11

Steve Tjoa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!