Created
July 29, 2023 05:52
-
-
Save LuisArteaga/b03fbe9056536356aa892f6d6805e6c8 to your computer and use it in GitHub Desktop.
The code creates a dataframe, encrypts one of the columns, and then creates two more dataframes with only the encrypted and decrypted columns.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pandas as pd | |
from cryptography.fernet import Fernet | |
# Create a test dataframe with 3 columns. The first column is an index, the second are random float values and third are one of three types (Delta, Gamma, Vega) | |
test_df = pd.DataFrame( | |
{ | |
"index": [1, 2, 3], | |
"trader_name": ['Luis Arteaga', 'Peter Meier', 'Max Mustermann'], | |
"trader_group": ["Delta", "Gamma", "Vega"] | |
} | |
) | |
# Create a new dataframe called new_df out of test_df with an additional column that encrypt the column random_float | |
new_df = test_df.copy() | |
new_df["fernet_key_for_trader_name"] = new_df.apply(lambda x: Fernet.generate_key(), axis=1) | |
new_df["trader_name_in_bytes"] = new_df["trader_name"].apply(lambda x: bytes(x, encoding='ASCII')) | |
new_df["type_trader_name_in_bytes"] = new_df["trader_name_in_bytes"].apply(lambda x: type(x)) | |
new_df["encrypted_trader_name"] = new_df.apply( | |
lambda x: Fernet(x["fernet_key_for_trader_name"]).encrypt(x["trader_name_in_bytes"]), | |
axis=1, | |
) | |
# Create a dataframe from new_df with index, trader_group and the decryption of encrypted_trader_name | |
test_decrypt_df = pd.DataFrame() | |
test_decrypt_df["decrypted_trader_name"] = new_df.apply( | |
lambda x: Fernet(x["fernet_key_for_trader_name"]).decrypt(x["encrypted_trader_name"]), | |
axis=1, | |
result_type="expand", | |
) | |
# Create a new dataframe from new_df with only the columns index, fernet_key_for_trader_name | |
output1_df = new_df[["index", "fernet_key_for_trader_name"]] | |
# Create a new dataframe from new_df with only index, trader_group and encrypted_trader_name | |
output2_df = new_df[["index", "trader_group", "encrypted_trader_name"]] | |
print(test_decrypt_df) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment