如何用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]})
初始数据
| a | b | c | d |
|---|---|---|---|
| one | three | [1, 2] | [5, 6] |
| two | four | [3, 4] | NaN |
期望结果
| a | b | c | d |
|---|---|---|---|
| one | three | [1, 2] | [5, 6] |
| two | four | [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
相关产品推荐
相关产品推荐

