Reputation: 37
Following is my dataset:
Name Rate Stock
AB 32.8 0
CD 56.7 100
EF 34.7 0
GH 33.1 0
IJ 44.5 100
KL 33.6 0
I want to add another column Discount
that is 0.95 * Rate
. However, it can only use Rate
with Stock = 100
. It should keep reiterating the Discount
value until it finds the next Stock = 100
Here's my desired outcome:
Name Rate Stock Discount
AB 32.8 0
CD 56.7 100 53.87
EF 34.7 0 53.87
GH 33.1 0 53.87
IJ 44.5 100 42.28
KL 33.6 0 42.28
Little help will be appreciated! Thanks
Upvotes: 0
Views: 131
Reputation: 29742
One way using boolean indexing with ffill
:
df["Discount"] = df["Rate"][df["Stock"].eq(100)] * 0.95
df["Discount"] = df["Discount"].ffill().fillna("")
print(df)
Output:
Rate Stock Discount
0 32.8 0
1 56.7 100 53.865
2 34.7 0 53.865
3 33.1 0 53.865
4 44.5 100 42.275
5 33.6 0 42.275
Upvotes: 2
Reputation: 120399
You can try:
df['Discount'] = df["Rate"][df["Stock"].eq(100)].mul(0.95) \
.reindex(df.index).ffill()
>>> df
Name Rate Stock Discount
0 AB 32.8 0 NaN
1 CD 56.7 100 53.865
2 EF 34.7 0 53.865
3 GH 33.1 0 53.865
4 IJ 44.5 100 42.275
5 KL 33.6 0 42.275
Upvotes: 1