You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas:用NumPy数组填充DataFrame列中的缺失值

Solution to Fill Missing Values in Order with NumPy Array

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 where True flags missing values.
  • Filtering this Series and extracting .index gives 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:01:01