I want to forward fill the amount column based on times column. for example first value is 2800000.0 , i want this value to be filled 6 times.
amount times
2800000.0 6
nan 0 0
nan 0 0
nan 0 0
nan 0 0
nan 0 0
nan 0 0
4750000.0 4
nan 0 0
nan 0 0
nan 0 0
nan 0 0
nan 0 0
nan 0 0
Desired output:
amount times
2800000.0 6
2800000.0 0
2800000.0 0
2800000.0 0
2800000.0 0
2800000.0 0
2800000.0 0
4750000.0 4
4750000.0 0
4750000.0 0
4750000.0 0
4750000.0 0
nan 0 0
nan 0 0
First create groups by test non missing values with cumulative sum and pass to GroupBy.apply
with lambda function with Series.ffill
with limit by first value of times
per groups:
#if necessary convert strings t onumeric and NaNs
#df['amount'] = pd.to_numeric(df['amount'], errors='coerce')
print (df['amount'].dtype)
float64
g = df['amount'].notna().cumsum()
f = lambda x: x['amount'].ffill(limit=x['times'].iat[0])
df['amount'] = df.groupby(g, group_keys=False).apply(f)
print (df)
amount times
0 2800000.0 6
1 2800000.0 0
2 2800000.0 0
3 2800000.0 0
4 2800000.0 0
5 2800000.0 0
6 2800000.0 0
7 4750000.0 4
8 4750000.0 0
9 4750000.0 0
10 4750000.0 0
11 4750000.0 0
12 NaN 0
13 NaN 0
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.