鉴于我有一个熊猫系列,如果全部值为NaN或者全部值为零或NaN,我想用零填充NaN
例如,我想用零填充以下系列中的NaN。
0 0
1 0
2 NaN
3 NaN
4 NaN
5 NaN
6 NaN
7 NaN
8 NaN
但是,我会不想要填充(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),否则不。
考虑到熊猫有多强大,似乎可能有更好的方法来做到这一点。有没有人有任何建议干净有效地做到这一点?
感谢cᴏʟᴅsᴘᴇᴇᴅ
的潜在解决方案if s.dropna().eq(0).all():
s = s.fillna(0)
答案 0 :(得分:8)
如果只有0
和NaN
以及0
,您可以按fillna
和isna
进行比较:
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 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
答案 1 :(得分:2)
为空值创建掩码。检查掩码的长度是否等于系列的长度(在这种情况下,系列都是空值或为空)或者非空值都等于零。如果是这样,请使用系列中的原始索引创建一个新的零值系列。
nulls = s.isnull()
if len(nulls) == len(s) or s[~nulls].eq(0).all():
s = pd.Series(0, index=s.index)
<强>的时间设置强>
%%timeit s_ = pd.concat([s] * 100000)
nulls = s_.isnull()
if len(nulls) == len(s_) or s_[~nulls].eq(0).all():
s_ = pd.Series(0, index=s_.index)
# 100 loops, best of 3: 2.33 ms per loop
# OP's solution:
%%timeit s_ = pd.concat([s] * 100000)
if s_.dropna().eq(0).all():
s_ = s_.fillna(0)
# 10 loops, best of 3: 19.7 ms per loop
# @Jezrael's fastest solution:
%%timeit s_ = pd.concat([s] * 100000)
if set(s_.unique().astype(str)).issubset(['0.0','nan']):
s_ = pd.Series(0, index=s_.index)
# 1000 loops, best of 3: 4.58 ms per loop