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

如何用np.where为Pandas含NA的列填充与其他列等长的列表?

Pandas替换DataFrame中列的NA值为对应长度的字符串列表

我有一个Pandas DataFrame,其中d列存在NA值,需要将该列的NA值替换为与c列列表长度相同的'no_value'字符串列表。

初始代码

import pandas as pd
import numpy as np

df = pd.DataFrame({"a": ["one", "two"],
                   "b": ["three", "four"],
                   "c": [[1, 2], [3, 4]],
                   "d": [[5, 6], np.nan]})

初始数据

abcd
onethree[1, 2][5, 6]
twofour[3, 4]NaN

期望结果

abcd
onethree[1, 2][5, 6]
twofour[3, 4][no_value, no_value]

尝试过的失败方法

  • 方法一:
df["d"] = np.where(df.d.isna(),
                   ['no_value' for element in df.c],
                   df.d)
  • 方法二:
df["d"] = np.where(df.d.isna(),
                   ['no_value'] * len(df.c),
                   df.d)

正确解决方案

df['d'] = np.where(df.d.isna(), 
                   pd.Series([['no_value'] * len(lst) for lst in df.c]), 
                   df.d)

内容的提问来源于stack exchange,提问作者gernophil

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 17:44:50