Statement of Completion#6223fc81
Intro to Pandas for Data Analysis
medium
Finding Mersenne primes with Pandas
Resolution
Activities
In [1]:
import pandas as pd
import numpy as np
1) Read the prime numbers from primes1.csv
into a dataframe named primes_df
¶
In [2]:
primes_df = pd.read_csv('primes1.csv')
Generating "one less than powers of two"¶
Here's an example of how to check if a prime is a Mersenne prime programmatically:
In [4]:
p = 31
In [5]:
for i in range(1, p):
result = 2 ** i - 1
if result == p:
print(f"{p} is a Mersenne prime!")
break
elif result > p:
print(f"{p} is NOT a Mersenne prime :(")
break
31 is a Mersenne prime!
Try changing the number of p
until you understand how Mersenne primes are calculated. Next, let's find some M-primes using Pandas.
In [6]:
100_000 ** 2
Out[6]:
10000000000
2) Generate a DataFrame with a sequential list of integers¶
In [7]:
exp_df = pd.DataFrame(np.arange(1, 100_001, 1), columns=['n'])
3) Create the column 2^n
¶
In [11]:
exp_df['2^n'] = 2 ** exp_df['n']
4) Create the column 2^n - 1
¶
In [13]:
exp_df['2^n - 1'] = exp_df['2^n'] - 1
Finding Mersenne primes¶
5) Create a new column is_mersenne_prime
that contains ALL False
values¶
In [18]:
primes_df['is_mersenne_prime'] = False
6) Mark the Mersenne primes with a True
value¶
In [20]:
primes_df_backup = primes_df.copy()
In [38]:
primes_df.loc[primes_df['n'].isin(exp_df['2^n - 1']), 'is_mersenne_prime'] = True
In [37]:
primes_df = primes_df_backup.copy()
In [ ]: