Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4230866
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 21, 20262026-05-21T01:54:35+00:00 2026-05-21T01:54:35+00:00

How can I calculate matrix mean values along a matrix, but to remove nan

  • 0

How can I calculate matrix mean values along a matrix, but to remove nan values from calculation? (For R people, think na.rm = TRUE).

Here is my [non-]working example:

import numpy as np
dat = np.array([[1, 2, 3],
                [4, 5, np.nan],
                [np.nan, 6, np.nan],
                [np.nan, np.nan, np.nan]])
print(dat)
print(dat.mean(1))  # [  2.  nan  nan  nan]

With NaNs removed, my expected output would be:

array([ 2.,  4.5,  6.,  nan])
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-21T01:54:35+00:00Added an answer on May 21, 2026 at 1:54 am

    I think what you want is a masked array:

    dat = np.array([[1,2,3], [4,5,'nan'], ['nan',6,'nan'], ['nan','nan','nan']])
    mdat = np.ma.masked_array(dat,np.isnan(dat))
    mm = np.mean(mdat,axis=1)
    print mm.filled(np.nan) # the desired answer
    

    Edit: Combining all of the timing data

       from timeit import Timer
        
        setupstr="""
    import numpy as np
    from scipy.stats.stats import nanmean    
    dat = np.random.normal(size=(1000,1000))
    ii = np.ix_(np.random.randint(0,99,size=50),np.random.randint(0,99,size=50))
    dat[ii] = np.nan
    """  
    
        method1="""
    mdat = np.ma.masked_array(dat,np.isnan(dat))
    mm = np.mean(mdat,axis=1)
    mm.filled(np.nan)    
    """
        
        N = 2
        t1 = Timer(method1, setupstr).timeit(N)
        t2 = Timer("[np.mean([l for l in d if not np.isnan(l)]) for d in dat]", setupstr).timeit(N)
        t3 = Timer("np.array([r[np.isfinite(r)].mean() for r in dat])", setupstr).timeit(N)
        t4 = Timer("np.ma.masked_invalid(dat).mean(axis=1)", setupstr).timeit(N)
        t5 = Timer("nanmean(dat,axis=1)", setupstr).timeit(N)
        
        print 'Time: %f\tRatio: %f' % (t1,t1/t1 )
        print 'Time: %f\tRatio: %f' % (t2,t2/t1 )
        print 'Time: %f\tRatio: %f' % (t3,t3/t1 )
        print 'Time: %f\tRatio: %f' % (t4,t4/t1 )
        print 'Time: %f\tRatio: %f' % (t5,t5/t1 )
    

    Returns:

    Time: 0.045454  Ratio: 1.000000
    Time: 8.179479  Ratio: 179.950595
    Time: 0.060988  Ratio: 1.341755
    Time: 0.070955  Ratio: 1.561029
    Time: 0.065152  Ratio: 1.433364
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I can calculate the size of the files in a tarfile in this way:
Can someone explain with an example how we can calculate the time and space
Hi i was wondering if anyone knows how i can calculate the difference between
I am planning to develop an application that can calculate the limit of an
How can I calculate a point (X,Y) a specified distance away, on a rotated
How can I calculate the number of differences between two NSStrings. Example: NSString 1
How can you calculate the following Friday at 3am as a datetime object? Clarification:
how can i calculate the total disc space available + free space + used
how can i calculate the polynomial that has the tangent lines (1) y =
How can i calculate the size of only some rows for each table? For

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.