gpt4 book ai didi

python - 循环遍历多个值以填充 Pandas Dataframe 中的 NaN

转载 作者:行者123 更新时间:2023-11-30 22:00:54 26 4
gpt4 key购买 nike

我知道我无法用列表填充 NaN,如 documentation 中所述。对于fillna。那么,使用值列表来填充 NaN 的首选方法是什么?期望的行为是遍历列表并一次填充一个 NaN;如果 NaN 数量多于列表中的数量,则重新开始。示例:

np.random.seed(0)
s = pd.Series(np.random.randint(0,100, 50))
s.loc[s > 25] = np.nan
s.fillna([10, 20, 30]) # Produces TypeError

期望的输出:

0   10
1 20
2 30
3 10
4 20
5 9.0
6 30
7 21.0
8 10

等等

这不是内置的,因为它很难矢量化吗?就其值(value)而言,这只是理论上的,我没有实际数据。

最佳答案

使用

s.loc[s.isna()]=[10,20,30]*(s.isna().sum()//3)+[10,20,30][:s.isna().sum()%3]
s
Out[271]:
0 10.0
1 20.0
2 30.0
3 10.0
4 20.0
5 9.0
6 30.0
...

关于python - 循环遍历多个值以填充 Pandas Dataframe 中的 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54203125/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com