Pandas:用NumPy数组填充DataFrame列中的缺失值
Absolutely, there's a straightforward way to do this! The key is to target the positions of the missing values in your DataFrame column and assign the NumPy array values directly to those positions in order. Here's how you can implement it:
Step-by-Step Example
First, let's set up sample data to demonstrate the workflow:
import pandas as pd import numpy as np # Create a DataFrame with k=3 missing values (n=6 > k) df = pd.DataFrame({'target_col': [10, np.nan, 30, np.nan, 50, np.nan]}) # Your NumPy array of size k=3 to fill the gaps fill_array = np.array([20, 40, 60])
Now apply the filling logic:
# Get the indices of missing values in the column nan_indices = df['target_col'].isna()[df['target_col'].isna()].index # Assign the array values to the missing positions df.loc[nan_indices, 'target_col'] = fill_array
After running this code, your target_col will be [10, 20, 30, 40, 50, 60]—exactly filling the first missing value with the first array element, second missing with second element, and so on.
How It Works
df['target_col'].isna()generates a boolean Series whereTrueflags missing values.- Filtering this Series and extracting
.indexgives us the exact positions of missing values in the order they appear in the DataFrame. df.loc[nan_indices, 'target_col']targets those specific rows, and assigning the NumPy array fills the gaps in sequence.
Optional Safety Check
To ensure the number of missing values matches your array length (a good practice even if you're confident in the counts):
if len(nan_indices) != len(fill_array): raise ValueError("Number of missing values doesn't match the fill array length!")
This method is efficient, readable, and avoids unnecessary loops while preserving the order you need.
内容的提问来源于stack exchange,提问作者aygestan

