gpt4 book ai didi

python - Pandas 使用最接近的方法对 bool 值进行插值

转载 作者:行者123 更新时间:2023-12-01 03:28:43 25 4
gpt4 key购买 nike

如何使用最近的方法在 pandas 中插入 bool 值?代码如下:

import pandas as pd
import numpy as np

df = pd.DataFrame({'b': np.random.rand(10) > 0.5})
df2 = df.iloc[[2,5,6,8]]
df2.reindex(df.index).interpolate('nearest')

产生错误:

TypeError: Cannot interpolate with all NaNs.

最佳答案

来自 Nickil Maveli 的评论答案,使用以下内容,

import pandas as pd
import numpy as np

df = pd.DataFrame({'b': np.random.rand(10) > 0.5})
df2 = df.iloc[[2,5,6,8]]
df2.reindex(df.index, method='nearest')

回答你的问题,

why did my approach failed?

我相信这与 NaN 是 np.nan 因此是 float 类型有关。当使用reindex时,它会在将其变为NaN之前填充任何可能为NaN的内容。因此,使用原始方法会创建 floatbool* 的混合数组。

看看我们如何在 bool 上进行插值

df2.reindex(df.index).astype(bool).interpolate('nearest')

Out[1]:

b
0 True
1 True
2 True
3 True
4 True
5 False
6 False
7 True
8 False
9 True

或仅使用 float

df2.reindex(df.index).astype(float).interpolate('nearest')

Out[2]:

b
0 NaN
1 NaN
2 1.0
3 1.0
4 1.0
5 1.0
6 0.0
7 0.0
8 0.0
9 NaN

请注意,bool 的行为相当意外,因为它用 True 填充 NaN。因此,原来的答案似乎最有效。

<小时/>

*这与错误消息所说的不太一致,所以我可能有点偏离,但我认为总体概念是正确的。

关于python - Pandas 使用最接近的方法对 bool 值进行插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41186869/

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