I want to check if the value of a column in a dataframe is equal to 0 and if it is 0, I want to substitute the previous row's value of that column.
Suppose my data is as follows,
a=[0,0,1,2,5,6,0,0,8,9,0,11,0,13]
Output should be
a=[0,0,1,2,5,6,6,6,8,9,9,11,11,13]
I tried the following command,
a = a.replace(0, np.NaN).ffill()
but I am getting,
a=[NaN,NaN,1,2,5,6,6,6,8,9,9,11,11,13]
I can't use drop_duplicates because the values would occur again in my array. So I need to check the previous value alone and do the calculation.
Can anybody help me with this?
Thanks
This should do the trick.
previousValue = 0
for i in range(len(a)):
if a[i] == 0:
a[i] = previousValue
else:
previousValue = a[i]
Or the more concise way would be
for i in range(1, len(a)):
if a[i] == 0:
a[i] = a[i-1]
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.