How to Remove rows in Numpy array that contains non-numeric values?

How to Remove rows in Numpy array that contains non-numeric values?

To remove rows in a NumPy array that contain non-numeric values, you can use a combination of boolean indexing and the np.isnan() function.

Here's how you can do it:

  1. First, convert all non-numeric values in the array to nan.
  2. Then, use np.isnan() to get a boolean mask indicating where the nan values are.
  3. Remove rows containing any nan values.

Here's a step-by-step example:

import numpy as np # Sample array with mixed data data = np.array([ [1, 2, 3], [4, 'a', 6], [7, 8, 9], [10, 11, 'b'] ]) # Convert non-numeric values to NaN data_numeric = np.full(data.shape, np.nan, dtype=float) mask = np.char.isnumeric(data) rows, cols = np.where(mask) data_numeric[rows, cols] = data[mask] # Remove rows with NaN filtered_data = data_numeric[~np.isnan(data_numeric).any(axis=1)] print(filtered_data) 

This will give you:

[[ 1. 2. 3.] [ 7. 8. 9.]] 

Only the rows without non-numeric values are retained in the filtered_data array.


More Tags

ejs verification export format-specifiers stored-procedures dynamically-generated alarmmanager hosting http-status-code-410 redux

More Programming Guides

Other Guides

More Programming Examples