gpt4 book ai didi

python - 如果系列是全 nan,或者剩余的非 nan 条目为零,如何有效地填充 na(0)?

转载 作者:太空狗 更新时间:2023-10-29 20:53:08 24 4
gpt4 key购买 nike

鉴于我有一个 pandas 系列,如果 all 值是 NaN 或者如果 all 值是零或 NaN,我想用零填充 NaN .

例如,我想用零填充以下 Series 中的 NaN。

0       0
1 0
2 NaN
3 NaN
4 NaN
5 NaN
6 NaN
7 NaN
8 NaN

但是,我不想填充na(0)以下系列:

0       0
1 0
2 2
3 0
4 NaN
5 NaN
6 NaN
7 NaN
8 NaN

我正在查看文档,似乎我可以使用 pandas.Series.value_counts 来确保值仅为 0 和 NaN,然后​​简单地调用 fillna(0)。换句话说,我想检查是否set(s.unique().astype(str)).issubset(['0.0','nan']), THEN fillna(0), 否则不。

考虑到 pandas 的强大,似乎有更好的方法来做到这一点。有没有人有任何建议来干净高效地执行此操作?

感谢 cᴏʟᴅsᴘᴇᴇᴅ 的潜在解决方案

if s.dropna().eq(0).all():
s = s.fillna(0)

最佳答案

您可以通过0isna 进行比较如果只有 NaN0 然后是 fillna:

if ((s == 0) | (s.isna())).all():
s = pd.Series(0, index=s.index)

或者比较唯一值:

if pd.Series(s.unique()).fillna(0).eq(0).all():
s = pd.Series(0, index=s.index)

@cᴏʟᴅsᴘᴇᴇᴅ 解决方案,谢谢 - 比较没有 NaN 的系列与 dropna :

 if s.dropna().eq(0).all():
s = pd.Series(0, index=s.index)

问题的解决方案 - 需要转换为 string,因为 problem with compare with NaNs :

if set(s.unique().astype(str)).issubset(['0.0','nan']):

s = pd.Series(0, index=s.index)

时间:

s = pd.Series(np.random.choice([0,np.nan], size=10000))

In [68]: %timeit ((s == 0) | (s.isna())).all()
The slowest run took 4.85 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 574 µs per loop

In [69]: %timeit pd.Series(s.unique()).fillna(0).eq(0).all()
1000 loops, best of 3: 587 µs per loop

In [70]: %timeit s.dropna().eq(0).all()
The slowest run took 4.65 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 774 µs per loop

In [71]: %timeit set(s.unique().astype(str)).issubset(['0.0','nan'])
The slowest run took 5.78 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 157 µs per loop

关于python - 如果系列是全 nan,或者剩余的非 nan 条目为零,如何有效地填充 na(0)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49973811/

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