您可以通过0
and isna
if only NaN
s 0
and then进行比较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
s 的系列与dropna
:
if s.dropna().eq(0).all():
s = pd.Series(0, index=s.index)
问题的解决方案 - 需要转换为string
s,因为与NaN
s比较的问题:
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