What's Happening In This Piece Of Code From Documentation?
Solution 1:
You can check DataFrame.where
:
cond : boolean Series/DataFrame, array-like, or callable Where cond is True, keep the original value. Where False, replace with corresponding value from other. If cond is callable, it is computed on the Series/DataFrame and should return boolean Series/DataFrame or array. The callable must not change input Series/DataFrame (though pandas doesn’t check it).
other : scalar, Series/DataFrame, or callable Entries where cond is False are replaced with corresponding value from other. If other is callable, it is computed on the Series/DataFrame and should return scalar or Series/DataFrame. The callable must not change input Series/DataFrame (though pandas doesn’t check it).
So it means it replace False
value of mask by other
, here -1000
.
Sample:
df = pd.DataFrame({'AAA': [4, 5, 6, 7], 'BBB': [4, 11, 0, 8], 'CCC': [2000, 45, 555, 85]})
print (df)
AAA BBB CCC
044200015114526055537885
df_mask = pd.DataFrame({'AAA': [True] * 4,
'BBB': [False] * 4,
'CCC': [True, False] * 2})
print (df.where(df_mask, -1000))
AAA BBB CCC
04 -1000200015 -1000 -100026 -100055537 -1000 -1000
If no values in other
there is replacement to NaN
s:
print (df.where(df_mask))
AAA BBB CCC
04NaN2000.015NaNNaN26NaN555.037NaNNaN
You can also pass mask with compare values, e.g.:
print (df.where(df > 10, -1000))
AAA BBB CCC
0 -1000 -1000 2000
1 -1000 11 45
2 -1000 -1000 555
3 -1000 -1000 85
Solution 2:
do print(df_mask)
You will get the dataframe as below
AAA BBB CCC
0TrueFalseTrue1TrueFalseFalse2TrueFalseTrue3TrueFalseFalse
with df.where(df_mask, -1000)
, you are replacing False
values with -1000 with final out put as below
AAABBBCCC04-1000200015-1000-100026-100055537-1000-1000
Post a Comment for "What's Happening In This Piece Of Code From Documentation?"