0
m = np.array([[[1,2],[2,1]], [[1,1],[2,1]]])

array([[[1, 2],
        [2, 1]],

       [[1, 1],
        [2, 1]]])



m2 = np.array([[[0.4,0.5],[0.2,0.3]], [[0.3,0.4],[0.5,0.5]]])

array([[[ 0.4,  0.5],
        [ 0.2,  0.3]],

       [[ 0.3,  0.4],
        [ 0.5,  0.5]]])

How can I calculate the mean of m2 for each unique element of m? I could write a list comprehension to loop through the elements of m, but I was wondering if there was a more straightforward way to do this. Is np.ma.masked_array appropriate in this case?

This is what I'm trying to achieve

1: np.mean(m2[m==1])
2: np.mean(m2[m==2])

this is fine for a couple of elements, but if I have 100, then it becomes cumbersome. I could write a list comprehension, but was hoping for a better alternative.

4
  • Could you include an example code of what you are trying to achieve here? Commented Mar 26, 2019 at 19:45
  • It's unclear what you're asking. Please provide a minimal reproducible example Commented Mar 26, 2019 at 19:45
  • To further the previous comments, it's not clear to me at all how m and m2 are related Commented Mar 26, 2019 at 19:53
  • sorry for not being clear. I have updated the question with an example Commented Mar 26, 2019 at 19:59

2 Answers 2

1
[np.mean(m2[m==i]) for i in np.unique(m)]
Sign up to request clarification or add additional context in comments.

Comments

0

Pandas give you a fast and elegant solution :

import pandas as pd    
df = pd.DataFrame(index=m.ravel(),data=m2.ravel())    
df.groupby(level=0).mean() 

#      0
#1  0.38
#2  0.40

it runs in 30 ms with:

m = np.random.randint(100,size=(100,100,100))
m2 = np.random.random((100,100,100))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.