如何在NumPy数组的指定索引位置恢复NaN值?
Got it, let's break down how to get your arrays back to the original (366,) shape with NaNs in their original spots. The key here is keeping track of where the NaNs were in the original array before you removed them—this lets us map the trimmed/interpolated data back correctly.
Step 1: Save the original NaN mask first (critical!)
If you haven't overwritten your original data array yet, start by capturing which indices were NaN. If you did overwrite it, you'll need to reload or recreate the original array first to get this mask.
import numpy as np # Assume original_data is your initial (366,) array with NaNs original_data = np.array([17., np.nan, 8.1, 25.1, np.nan, 6.9, np.nan, 27.1, 46.6, 34.1, 25.7, np.nan, 25.3]) # example snippet mask = np.isnan(original_data) # This array will be True where original had NaNs
Step 2: Process your data (as you already did)
Extract non-NaN values and run your interpolation:
# Extract non-NaN values (this is your (283,) data array) non_nan_data = original_data[~mask] # Run your interpolation to get interpolated_data (283,) # (You already have this part done, so just use your existing interpolated_data variable) interpolated_data = np.array([16, 7.1, 24.1, 7.9, 26.1, 45.6, 33.1, 27.7, 24.3]) # example snippet
Step 3: Restore both arrays to original shape
We'll create new arrays with the original size, fill them with NaNs, then populate the non-NaN positions with your processed data:
# Restore original data (back to (366,) with NaNs in original spots) restored_data = np.full_like(original_data, np.nan) restored_data[~mask] = non_nan_data # Restore interpolated data (same shape, NaNs in original positions) restored_interpolated = np.full_like(original_data, np.nan) restored_interpolated[~mask] = interpolated_data
How this works:
- The
maskarray acts as a blueprint: it tells us exactly where to leave NaNs and where to insert your non-NaN/interpolated values. np.full_likecreates a new array with the same shape and dtype as the original, filled with NaNs.- We use
~mask(the inverse of the NaN mask) to index into the new arrays and place our trimmed/interpolated data in the correct positions.
This will give you exactly the two arrays you're expecting:
restored_datamatches your original (366,) array with all NaNs in their original indices.restored_interpolatedhas your interpolated values in the non-NaN positions, with NaNs filling the original missing spots.
内容的提问来源于stack exchange,提问作者Javier

