I have a dataframe with several columns and a series whose value are the index of the first non-nan value of the dataframe:
dataframe x:
a b c d e f g h
1 nan nan 2 nan nan nan nan nan
2 nan 2 nan 10 23 nan nan nan
3 3 nan 23 42 232 3 nan 5
series y:
a 3
b 2
c 1
d 2
e 2
f 3
g nan
h 3
now I want to assign 0 with all the value after first non-nan value(include the first non-nan value) by the value of series(whose value are the index of the first non-nan value of the dataframe x)
result is
a b c d e f g h
1 nan nan 0 nan nan nan nan nan
2 nan 0 0 0 0 nan nan nan
3 0 0 0 0 0 0 nan 0
I use applymap to deal with it,but applymap seems not to deal with index information,here is my code:
def mycode(x,y)
if x.index<=Y:
return 0
else:
return x
cal = x.applymap(lambda x: mycode(x,y))
You can use ffill
( fillna
with method='ffill'
) with clip
:
x = x.ffill().clip(0,0)
Alternative solutions with boolean mask and where
or mask
:
x = x.where(x.ffill().isnull(), 0)
x = x.mask(x.ffill().notnull(), 0)
print (x)
a b c d e f g h
1 NaN NaN 0.0 NaN NaN NaN NaN NaN
2 NaN 0.0 0.0 0.0 0.0 NaN NaN NaN
3 0.0 0.0 0.0 0.0 0.0 0.0 NaN 0.0
Detail:
print (x.ffill())
a b c d e f g h
1 NaN NaN 2.0 NaN NaN NaN NaN NaN
2 NaN 2.0 2.0 10.0 23.0 NaN NaN NaN
3 3.0 2.0 23.0 42.0 232.0 3.0 NaN 5.0
print (x.ffill().isnull())
a b c d e f g h
1 True True False True True True True True
2 True False False False False True True True
3 False False False False False False True False
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.