首页 > 解决方案 > 用数据框中的数组替换 NaN 值

问题描述

我试图用数组 [NaN, NaN, NaN] 替换数据框中的所有 NaN 值。但是正常的替换方法(df.replace)不起作用,因为 to_replace 和 value 的大小不同。

提前致谢 :)

标签: pythondataframereplacenan

解决方案


我想出了一些东西,应该可以:

import pandas as pd
import numpy as np

# Sample df with a NaN in column "y"
df = pd.DataFrame({"y": np.NaN, "x": ["Some Value"]})

# Get the nans
isna = df['y'].isna()

# Replace with series with list of (3) nans
df.loc[isna, 'y'] = pd.Series([[np.NaN, np.NaN, np.NaN]] * isna.sum()).values

print(df)

主要取自:https ://stackoverflow.com/a/61944174/5635941


推荐阅读