【问题标题】:Determine Prime Number in Python DataFrame确定 Python DataFrame 中的素数
【发布时间】:2020-11-14 14:15:12
【问题描述】:

我有这样的数据框:

      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

我需要知道相应的客户是否有资格获得优惠券。标准是如果 trx 是质数,则客户符合条件,否则不符合条件。数据框应该是这样的:

      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

我知道如何确定素数,但不知道在数据框中。提前谢谢你

【问题讨论】:

  • 编写一个函数,当一个数字是素数时返回'eligible',否则返回'not eligible',然后使用Series.map(isprime),其中isprime是函数名或Series.apply(isprime)

标签: python pandas dataframe primes


【解决方案1】:

我从这里复制并粘贴了一个函数来确定一个数字是否为素数:
Python Prime number checker

然后我使用.apply() 将此函数应用于“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)

结果数据框:

    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

【讨论】:

  • 谢谢!这可行,但我稍微调整了功能。它将返回“合格”或“不合格”,而不是返回 True 或 False。只是轻微的调整,但总的来说谢谢
【解决方案2】:

为什么不使用 Sympy 的 isprime() 函数。

def is_prime(num):
    from sympy import isprime
    return "eligible" if isprime(num) else "not eligible"

df['Voucher'] = df['Trx'].apply(is_prime)

【讨论】:

    【解决方案3】:

    更快一点的方法是在df.Txnmap 字典中的minmax 中创建素数字典到df.Txnfilling na

    def isPrime(n):
        if n==2: return True
        if n==1 or n%2 == 0: return False
        else:
          for i in range(2, int(n**0.5)+1):
              if n %  i == 0:
                return False
          return True
    
    def get_primes_within(lower,upper):
      prime ={}
      for num in range(lower, upper + 1):
        if isPrime(num):
          prime[num] = 'eligible'
      return prime
    
    prime_dict =  get_primes_within(df.Trx.min(),df.Trx.max())
    
    >>> print(prime_dict)
    {7: 'eligible',
     11: 'eligible',
     13: 'eligible',
     17: 'eligible',
     19: 'eligible',
     23: 'eligible',
     29: 'eligible'}
    
    df['Voucher'] = df.Trx.map(prime_dict).fillna('not eligible')
    >>> print(df)
    
         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
    

    【讨论】:

      猜你喜欢
      • 2021-12-30
      • 2021-04-16
      • 2021-12-21
      • 1970-01-01
      • 1970-01-01
      • 2022-11-05
      • 2016-06-21
      • 1970-01-01
      • 2015-01-22
      相关资源
      最近更新 更多