'For loop giving the same value for the entire column
I am new to python and trying to run a for loop. I am trying to multiply any value in a column that is greater than 20 with .25 and anything greater than 5 with .15 and create a new column with that values. This is what I am doing but I get the same values for the entire column:
new_data = data[['restaurant_name', 'cost_of_the_order']].copy()
for x in new_data['cost_of_the_order']:
if x > 20:
data['revenue'] = x*.25
if x > 15 and x < 20:
data['revenue'] = x*.15
I get this:
restaurant_name cost_of_the_order revenue
0 Hangawi 30.75 6.305
1 Blue Ribbon Sushi Izakaya 12.08 6.305
2 Cafe Havana 12.23 6.305
3 Blue Ribbon Fried Chicken 29.20 6.305
4 Dirty Bird to Go 11.59 6.305
Solution 1:[1]
I changed a bit you code mainly because I didn't know what that data[ ] is. This is my solution:
import numpy as np
cost_of_the_order = [30.75, 12.8, 12.23, 29.20, 11.59]
restaurant_name = ['Hangawi', 'Blue Ribbon', 'Cafe Havana', 'Blue Ribbon 2', 'Birty Bird']
new_data = ['restaurant_name', 'cost_of_the_order'].copy()
revenue = []
for i in cost_of_the_order:
if 5 < i < 20:
revenue.append(i*.15)
elif i > 20:
revenue.append(i*.25)
np.hstack(revenue)
for x,y,z in zip(restaurant_name, cost_of_the_order, revenue):
print (x ,y ,z)
The output is:
Hangawi 30.75 7.6875
Blue Ribbon 12.8 1.92
Cafe Havana 12.23 1.8345
Blue Ribbon 2 29.2 7.3
Birty Bird 11.59 1.7385
I used a list to get all the results of the for loop and then we get the output as an array with numpy.
The last for loop isn't necessary, it could be used to make a similar output as yours, but u could even use pandas.
Hope this solve your problem
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
