I have dataframe like this:
Name Email Trx
0 John john.doe@gmail.com 30
1 Sarah sarah@gmail.com 7
2 Bob bob@yahoo.com 11
3 Chad chad@outlook.com 21
4 Karen karen@outlook.com 20
5 Dmitri dmitri@rocketmail.com 17
and I need to know whether the respective customer eligible for a voucher or not. The criteria is if the trx is a prime number, the customer is eligible, else it's not eligible. The dataframe should be like this:
Name Email Trx Voucher
0 John john.doe@gmail.com 30 not eligible
1 Sarah sarah@gmail.com 7 eligible
2 Bob bob@yahoo.com 11 eligible
3 Chad chad@outlook.com 21 not eligible
4 Karen karen@outlook.com 20 not eligible
5 Dmitri dmitri@rocketmail.com 17 eligible
I know how to determine prime number but not in a dataframe. Thank you in advance
I copy and pasted a function to find out if a number is prime from here:
Python Prime number checker
Then I use .apply() to apply this function to every value in column 'Trx':
def isprime(n):
'''check if integer n is a prime'''
# make sure n is a positive integer
n = abs(int(n))
# 0 and 1 are not primes
if n < 2:
return False
# 2 is the only even prime number
if n == 2:
return True
# all other even numbers are not primes
if not n & 1:
return False
# range starts with 3 and only needs to go up
# the square root of n for all odd numbers
for x in range(3, int(n**0.5) + 1, 2):
if n % x == 0:
return False
return True
df['Voucher'] = df['Trx'].apply(isprime)
Resulting dataframe:
Name Email Trx Voucher
0 John john.doe@gmail.com 30 False
1 Sarah sarah@gmail.com 7 True
2 Bob bob@yahoo.com 11 True
3 Chad chad@outlook.com 21 False
4 Karen karen@outlook.com 20 False
5 Dmitri dmitri@rocketmail.com 17 True