【问题标题】:How to impute/replace missing values in a pandas DataFrame with a sequence of values?如何用一系列值估算/替换 pandas DataFrame 中的缺失值?
【发布时间】:2023-04-06 18:05:01
【问题描述】:

例如,假设我有这个 DataFrame:

Weights = pd.DataFrame({'Weight': [46, np.nan, 67, 62, np.nan, np.nan, 88, np.nan, 55, np.nan]})
Weights

    Weight
0   46.0
1   NaN
2   67.0
3   62.0
4   NaN
5   NaN
6   88.0
7   NaN
8   55.0
9   NaN

我想用以下值序列替换/估算 NaN 值:

replace = np.random.randint(45,90, size=(5,))
replace
array([85, 79, 68, 72, 52])

这样生成的 DateFrame 看起来像:

Weights

    Weight
0   46
1   85
2   67
3   62
4   79
5   68
6   88
7   72
8   55
9   52

我需要什么代码?这可以使用标准 python 代码、只使用 pandas 还是只使用 scikit-learn 来完成? 提前致谢。

【问题讨论】:

  • Weights.loc[Weights.Weight.isnull(), 'Weight'] = replace

标签: python python-3.x pandas


【解决方案1】:

我刚刚想通了

weights.replace({np.nan:replace})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-10
    • 1970-01-01
    • 2014-06-23
    • 2019-07-16
    • 2014-06-12
    相关资源
    最近更新 更多