Multiple If Statement in function not applying properly to Pandas dataframe - python

I have a table where I am trying to calculate if on a given day a carding attack occurred by looking at the current day's network decline count, network decline rate, and rolling seven day average of network approvals. Below is how I was calculating if it was a carding attack or not. However the results don't match the data.
def carding_attack(row):
if (row['network_decline_rate']>=30 & row['seven_day_average'] >= 681 & row['count_Network Decline']>=(row['seven_day_average']*4)):
return "Carding Attack 1"
elif (row['network_decline_rate']>=30 & row['seven_day_average'] >= 251 & row['seven_day_average'] <= 680 & row['count_Network Decline'] >= 2600):
return "Carding Attack 2"
elif (row['network_decline_rate']>=30 & row['seven_day_average'] >= 151 & row['seven_day_average'] <= 250 & row['count_Network Decline'] >= 2000):
return "Carding Attack 3"
elif (row['network_decline_rate']>=30 & row['seven_day_average'] >= 101 & row['seven_day_average'] <= 150 & row['count_Network Decline'] >= 1500):
return "Carding Attack 4"
elif (row['network_decline_rate']>=30 & row['seven_day_average'] >= 51 & row['seven_day_average'] <= 100 & row['count_Network Decline'] >= 750):
return "Carding Attack 5"
elif (row['network_decline_rate']>=30 & row['seven_day_average'] >= 11 & row['seven_day_average'] <= 50 & row['count_Network Decline'] >= 580):
return "Carding Attack 6"
elif (row['network_decline_rate']>=30 & row['seven_day_average'] >= 1 & row['seven_day_average'] <= 10 & row['count_Network Decline'] >= 250):
return "Carding Attack 7"
else:
return "Not a Carding Attack"
daily_network_counts['carding_attack'] = daily_network_counts.apply(carding_attack,axis=1)
Actual results which do not match what I want
This is what I was expecting it to look like.enter image description here

Related

Returns None instead of False

So I'm working on a question on CodingBat, a website that provides JS and Python practice problems. I've encountered a unexpected output. Btw here's the link to the question: https://codingbat.com/prob/p135815 . In theory my code should return False but it returns none when I put print(squirrel_play(50, False))
Code:
def squirrel_play(temp, is_summer):
if is_summer:
if temp <= 100:
if temp >= 60:
return True
elif temp <= 60:
return False
elif temp >= 100:
return False
if not is_summer:
if temp <= 90:
if temp >= 60:
return True
elif temp >= 90:
return False
elif temp <= 60:
return False
when I run that with print(squirrel_play(50, False)), I get None (I should get False)
Why???
With your parameter of is_summer of False, you're in the 2nd conditional block:
if not is_summer:
if temp <= 90:
if temp >= 60:
return True
elif temp >= 90:
return False
elif temp <= 60:
return False
Then follow this block:
is the temp less than 90? yes. so now we're in this block:
if temp <= 90:
if temp >= 60:
return True
What is happening here is that you never get to the elif temp <= 60 because you are in the first conditional instead. You could only ever get to the elif below if you didn't satisfy the first condition.
At the end of this if temp <= 90 block the entire conditional chain ends and your function returns the default value of None because you didn't provide another return value.
You can maybe more clearly see this by making the entire code read:
def squirrel_play(temp, is_summer):
if is_summer:
if temp <= 100:
if temp >= 60:
return True
elif temp <= 60:
return False
elif temp >= 100:
return False
if not is_summer:
if temp <= 90:
if temp >= 60:
return True
else:
return "This is where I'm returning with 50, and True as my parameters"
elif temp >= 90:
return False
elif temp <= 60:
return False
Did you try to debug it?
With squirrel_play(50, False) it will fall into:
def squirrel_play(temp, is_summer):
if is_summer:
if temp <= 100:
if temp >= 60:
return True
elif temp <= 60:
return False
elif temp >= 100:
return False
if not is_summer:
if temp <= 90:
if temp >= 60:
return True
# HERE ( 50 is less than 90 but not greater than 60 )
# and you have no return statement for this case
elif temp >= 90:
return False
elif temp <= 60:
return False
If you don't return a value from a Python function, None is returned by default. I believe that what is happening here is that because you are using elif statements, since the clause if not is_summer: if temp <= 90: is being entered, the final clause elif temp <= 60 is not being reached. Therefore the function gets passed all of the if/elif statements without returning a value, and returns None.
A simple solution is to replace all of the elifs with ifs. Then print(squirrel_play(50, False)) returns False (for me at least).
The way that you have currently coded it, in your
if temp <= 90:
if temp >= 60:
return True
elif ....
if the first if test evaluates True but the second one evaluates False, then no return statement is reached (bear in mind that the subsequent elif tests are not performed because the first if evaluated true), and the function therefore returns None.
In fact you can simplify the function making use of chained comparison operators:
def squirrel_play(temp, is_summer):
if is_summer:
return 60 <= temp <= 100
else:
return 60 <= temp <= 90

Issues with replicating results from R to python by writing customised function

I am trying to convert the R code to python by writing customised function or without function in python based on this following lines of code
customers_df$segment = "NA"
customers_df$segment[which(customers_df$recency > 365*3)] = "inactive"
customers_df$segment[which(customers_df$recency <= 365*3 & customers_df$recency > 365*2)] = "cold"
customers_df$segment[which(customers_df$recency <= 365*2 & customers_df$recency > 365*1)] = "warm"
customers_df$segment[which(customers_df$recency <= 365)] = "active"
customers_df$segment[which(customers_df$segment == "warm" & customers_df$first_purchase <= 365*2)] = "new warm"
customers_df$segment[which(customers_df$segment == "warm" & customers_df$amount < 100)] = "warm low value"
customers_df$segment[which(customers_df$segment == "warm" & customers_df$amount >= 100)] = "warm high value"
customers_df$segment[which(customers_df$segment == "active" & customers_df$first_purchase <= 365)] = "new active"
customers_df$segment[which(customers_df$segment == "active" & customers_df$amount < 100)] = "active low value"
customers_df$segment[which(customers_df$segment == "active" & customers_df$amount >= 100)] = "active high value"
table(customers_2015$segment)
active high value active low value cold inactive
573 3313 1903 9158
new active new warm warm high value warm low value
1512 938 119 901
Python Function
I tried to replicate the same code as above in python by writing function. However, I was not able to get the same categories as R as a well number in each category also differs.
def mang_segment (s):
if (s['recency'] > 365*3):
return ("inactive")
elif (s['recency'] <= 365*3) & (s['recency'] > 365*2):
return ("cold")
elif (s['recency'] <= 365*2) & (s['recency'] > 365*1):
return ("warm")
elif (s['recency'] <= 365):
return ("active")
def mang_segment_up (s):
# if (s['recency'] > 365*3):
# return ("inactive")
# elif (s['recency'] <= 365*3 & s['recency'] > 365*2):
# return ("cold")
# elif (s['recency'] <= 365*2 & s['recency'] > 365*1):
# return ("warm")
if (s['segment'] == "warm") & (s['first_purchase'] <= 365*2):
return ("new warm")
elif (s['segment'] == "warm") & (s['amount'] < 100):
return ("warm low value")
elif (s['segment'] == "warm") & (s['amount'] >= 100):
return ("warm high value")
elif (s['segment'] == "active") & (s['first_purchase'] <= 365):
return ("new active")
elif (s['segment'] == "active") & (s['amount'] < 100):
return ("active low value")
elif (s['segment'] == "active") & (s['amount'] >= 100):
return ("active high value")
active low value 19664
warm low value 4083
active high value 3374
new active 1581
new warm 980
warm high value 561
Any pointer/suggestion would be appreciated.
Thanks in advance
I am a little confused about the purpose of the function (and if it is working as you expect). If you are seeking to mimic your R code within a function, your syntax can line up much closer with your initial code than it currently is. Assuming you are using panads/numpy:
import numpy as np
import pandas as pd
#toy example
s = pd.DataFrame({'rec' : [2000, 1500, 3000, 750]})
def mang_segment (s):
s.loc[(s['rec'] > 365*3), 'seg'] = "inactive" # creating a new column seg with our values
s.loc[(s['rec'] <= 365*3) & (s['rec'] > 365*2), 'seg'] = "cold"
#etc...
#run function
mang_segment(s)
#get value counts
s['seg'].value_counts()
Here we add a column to our dataframe to capture our values, which we can later summarize. This is different than the return function that, if it were working and call appropriately, would not assign it directly to your data frame.
There are other function and ways to get it at this, too. Check out np.where as another option.

I keep getting None

My code:
def get_feedback(mark, out_of):
percentage = int((mark / out_of) * 100)
if percentage >= 80:
print("Excellent")
if 60 < percentage < 70:
print("Good")
if 50 < percentage < 59:
print("Pass")
if percentage < 50:
print("Not a pass")
I know I have to use a return statement somewhere but I'm not really sure how it works or when to use it. If anyone could help, that would be great thank you!
def get_feedback(mark, out_of):
percentage = int((mark / out_of) * 100)
remark = ''
if percentage >= 80:
remark = "Excellent"
elif 60 <= percentage <= 79:
remark = "Good"
elif 50 <= percentage <= 59:
remark = "Pass"
else percentage < 50:
remark = "Not a pass"
return remark
Some suggestions:
I believe you need inclusive range, so include <= instead of <
If one condition satisfies, no need to check the rest of the conditions. So instead of using if for every check, use if - elif- else checks.
Also your question says the range between 60 and 79 for grade 'Good'. You haven't checked it.
Use return in place of print. Example :- return "Excellent".
Another way to do it :
def get_feedback(mark, out_of):
percentage = int((mark / out_of) * 100)
if percentage >= 80:
return "Excellent"
elif 60 <= percentage <= 79:
return "Good"
elif 50 <= percentage <= 59:
return "Pass"
else:
return "Not a pass"
You can make a variable to represent the value of its condition.
def get_feedback(mark, out_of):
percentage = int((mark / out_of) * 100)
if percentage >= 80:
feedback = "Excellent"
elif 60 < percentage < 70:
feedback = "Good"
elif 50 < percentage < 59:
feedback = "Pass"
elif percentage < 50:
feedback = "Not a pass"
return print(feedback)
At the very end, we use return to give us the result of the function. Also, notice that I used elif statements, which are faster than just using if statements.

Why is there coming up the SyntaxError with if and elif[

I am trying to make a quiz in python. But the prizes cause errors.
I tried deleting the red spot but it changed location.
if (raha <= 1000):
webbrowser.open('http://www.rrrgggbbb.com')
elif (2500 >= raha = > 1000):
webbrowser.open('https://codepen.io/akm2/full/rHIsa')
elif (3000 >= raha = > 2500):
webbrowser.open('https://turbo.fish/')
elif (4000 >= raha = > 4500):
webbrowser.open('https://turbo.fish/')
elif (3000 >= raha = > 4000):
webbrowser.open('https://hooooooooo.com/')
elif (4500 >= raha = > 6000):
webbrowser.open('https://trypap.com/')
elif (6000 >= raha = > 8000):
webbrowser.open('https://chrismckenzie.com/')
elif (8000 <= raha):
print("sa võid auhinna ise valida. Keri alla")
time.sleep(2)
webbrowser.open('https://makefrontendshitagain.party/')
it should not say bad file descriptor
The error is in comparison, not in if-elif. It has to be >= or <=. => and =< are invalid. In some places, you have also put a space between = and >. So, >= is valid but > =" is not.
Use this:
if raha <= 1000:
webbrowser.open('http://www.rrrgggbbb.com')
elif 2500 >= raha >= 1000:
webbrowser.open('https://codepen.io/akm2/full/rHIsa')
elif 3000 >= raha >= 2500:
webbrowser.open('https://turbo.fish/')
elif 4000 >= raha >= 4500:
webbrowser.open('https://turbo.fish/')
elif 3000 >= raha >= 4000:
webbrowser.open('https://hooooooooo.com/')
elif 4500 >= raha >= 6000:
webbrowser.open('https://trypap.com/')
elif 6000 >= raha >= 8000:
webbrowser.open('https://chrismckenzie.com/')
elif 8000 <= raha:
print("sa võid auhinna ise valida. Keri alla")
time.sleep(2)
webbrowser.open('https://makefrontendshitagain.party/')

Python Ranking Program Using Numbers

The promoter wants to be able to classify donors based on how much they have contributed to the overall goal of the campaign.
Write a function easy_donor_rank(percent_donated) that takes a number indicating percent donated and returns a string containing the rank attained by giving such a donation.
For example, the function call easy_donor_rank(1.0) should return the string 'Bronze'.
See the table below to see the list of donor ranks.
Donor Classification
Donation Percentage Donor Rank
0% or less
Error Less than 2% Bronze
2% to 15% inclusive Silver more than 15% Gold
The code I have right now works but I always get a "None" in the end of every output
def easy_donor_rank(percent_donated):
if percent_donated <= 0:
print("Error")
if percent_donated < 2:
print("Bronze")
elif percent_donated >= 2 and percent_donated <= 15:
print("Silver")
else:
print("Gold")
Basically, your code works for me. I made a small modification only for your if condition. I change the second if to elif.
def easy_donor_rank(percent_donated):
if percent_donated <= 0:
print("Error")
elif percent_donated < 2:
print("Bronze")
elif percent_donated <= 15:
print("Silver")
else:
print("Gold")
it's work in python 3.6
def easy_donor_rank(percent_donated):
if percent_donated <= 0:
return "Error"
elif percent_donated < 2:
return ("Bronze")
elif percent_donated >= 2 and percent_donated <= 15:
return ("Silver")
else:
return ("Gold")
The code I have right now works but I always get a "None" in the end
of every output.
I'm going to assume that you are trying to print the return of easy_donor_rank.
$ cat test.py
def easy_donor_rank(percent_donated):
if percent_donated <= 0:
print("Error")
if percent_donated < 2:
print("Bronze")
elif percent_donated >= 2 and percent_donated <= 15:
print("Silver")
else:
print("Gold")
print(easy_donor_rank(1.2))
But because you don't return anything, it will return None, so None gets printed.
$ python3 test.py
Bronze
None
You just need to return the result instead of printing it inside the function.
See What is the purpose of the return statement?
$ cat test.py
def easy_donor_rank(percent_donated):
if percent_donated <= 0:
return "Error"
if percent_donated < 2:
return "Bronze"
elif percent_donated >= 2 and percent_donated <= 15:
return ("Silver")
else:
return "Gold"
print(easy_donor_rank(1.2))
$ python3 test.py
Bronze

Categories

Resources