J'ai deux df avec un price et un autre df avec price ranges .
Expected output
name price final_amount
0 anthony 5 15
1 paul 16 36
2 marcus 25 55
3 bruno 45 85
J'essaie d'ajouter le montant au prix si price colonne de price entre dans cette catégorie. Exemple:
name - marcus a le prix 25 , qui se situe entre 20-30 , alors ajoutez 30 au price .
price_df
name price
0 anthony 5
1 paul 16
2 marcus 25
3 bruno 45
range_df
add_amount min max
0 10 0 10
1 20 10 20
2 30 20 30
3 40 30 50
3 Réponses :
Je pense que vous pouvez utiliser pd.cut :
name price final_amount 0 anthony 5 15.0 1 paul 16 36.0 2 marcus 25 55.0 3 bruno 45 85.0
Production:
price_bins = [range_df['min'][0]] + list(range_df['max'])
price_df['final_amount'] = price_df['price'] + pd.cut(price_df['price'],
bins= price_bins,
labels=range_df['add_amount']
).astype(float)
Vous pouvez utiliser merge_asof et définir la direction pour avancer:
s = (pd.merge_asof(price_df, range_df, left_on="price", right_on="max", direction="forward")
.drop(["min", "max"], axis=1))
print (s.assign(final_amount=s["price"]+s["add_amount"]))
name price add_amount final_amount
0 anthony 5 10 15
1 paul 16 20 36
2 marcus 25 30 55
3 bruno 45 40 85
une autre façon de résoudre votre problème:
l = [] # creat a list for to add final amount
for i in price_df['price']:
for j in range(len(range_df['min'])):
if i < range_df['max'][j] and i > range_df['min'][j]:
l.append(i + range_df['add_amount'][j]) # append the variable between min a max to l
else:
print('-->', range_df['add_amount'][j])
price_df['final_amount'] = l # make a coulmn named final_amount