Given that I have a pandas Series, I want to fill the NaNs with zero if either all the values are NaN or if all the values are either zero or NaN.
For example, I would want to fill the NaNs in the following Series with zeroes.
0 0
1 0
2 NaN
3 NaN
4 NaN
5 NaN
6 NaN
7 NaN
8 NaN
But, I would not want to fillna(0) the following Series:
0 0
1 0
2 2
3 0
4 NaN
5 NaN
6 NaN
7 NaN
8 NaN
I was looking at the documentation and it seems like I could use pandas.Series.value_counts to ensure the values are only 0 and NaN, and then simply call fillna(0).In other words, I am looking to check if set(s.unique().astype(str)).issubset(['0.0','nan']), THEN fillna(0), otherwise do not.
Considering how powerful pandas is, it seemed like a there may be a better way to do this. Does anyone have any suggestions to do this cleanly and efficiently?
Potential solution thanks to cᴏʟᴅsᴘᴇᴇᴅ
if s.dropna().eq(0).all():
s = s.fillna(0)