How to encode and decode a column in python pandas?

2024/9/22 16:38:15
load = pd.DataFrame({'A':list('abcdef'),'B':[4,5,4,5,5,4],'C':[7,8,9,4,2,0],'D':[1,3,5,4,2,0],'E':[5,3,6,9,2,4],'F':list('aaabbb')})

How to encode and decode column F.

Expected Output:

Should have two more columns with encoded and decoded values

    A   B   C   D   E   F Encoded_Column           Decoded_Column
0   a   4   7   1   5   a   <!--Encoded Value-->    a
1   b   5   8   3   3   a   <!--Encoded Value-->    a
2   c   4   9   5   6   a   <!--Encoded Value-->    a 
3   d   5   4   4   9   b   <!--Encoded Value-->    b
4   e   5   2   2   2   b   <!--Encoded Value-->    b
5   f   4   0   0   4   b   <!--Encoded Value-->    b
Answer

You can use this solution implemented to pandas by Series.apply:

from Crypto.Cipher import XOR
import base64def encrypt(key, plaintext):cipher = XOR.new(key)return base64.b64encode(cipher.encrypt(plaintext))def decrypt(key, ciphertext):cipher = XOR.new(key)return cipher.decrypt(base64.b64decode(ciphertext))load['Encoded_Column'] = load['F'].apply(lambda x: encrypt('password',x))
load['Decoded_Column'] = (load['Encoded_Column'].apply(lambda x: decrypt('password', x)).str.decode("utf-8"))
print (load)A  B  C  D  E  F Encoded_Column Decoded_Column
0  a  4  7  1  5  a        b'EQ=='              a
1  b  5  8  3  3  a        b'EQ=='              a
2  c  4  9  5  6  a        b'EQ=='              a
3  d  5  4  4  9  b        b'Eg=='              b
4  e  5  2  2  2  b        b'Eg=='              b
5  f  4  0  0  4  b        b'Eg=='              b

Another solution:

import base64
def encode(key, clear):enc = []for i in range(len(clear)):key_c = key[i % len(key)]enc_c = chr((ord(clear[i]) + ord(key_c)) % 256)enc.append(enc_c)return base64.urlsafe_b64encode("".join(enc).encode()).decode()def decode(key, enc):dec = []enc = base64.urlsafe_b64decode(enc).decode()for i in range(len(enc)):key_c = key[i % len(key)]dec_c = chr((256 + ord(enc[i]) - ord(key_c)) % 256)dec.append(dec_c)return "".join(dec)load['Encoded_Column'] = load['F'].apply(lambda x: encode('password',x))
load['Decoded_Column'] = load['Encoded_Column'].apply(lambda x: decode('password', x))

Or use list comprehension:

load['Encoded_Column'] = [encode('password',x) for x in load['F']]
load['Decoded_Column'] = [decode('password', x) for x in load['Encoded_Column']]print (load)A  B  C  D  E  F Encoded_Column Decoded_Column
0  a  4  7  1  5  a           w5E=              a
1  b  5  8  3  3  a           w5E=              a
2  c  4  9  5  6  a           w5E=              a
3  d  5  4  4  9  b           w5I=              b
4  e  5  2  2  2  b           w5I=              b
5  f  4  0  0  4  b           w5I=              b
https://en.xdnf.cn/q/119112.html

Related Q&A

Pygame module not found [duplicate]

This question already has answers here:Why do I get a "ModuleNotFoundError" in VS Code despite the fact that I already installed the module?(23 answers)Closed 3 months ago.I have installed p…

Working with Lists and tuples

My data looks like:X=[1,2,3,4]But I need it to look like: Y=[(1,2,3,4)]How does one do this in python?

Football pygame, need help on timer [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 4 years ago.Improve…

Unable to Install GDAL Using PIP on Python

Im trying to install gdal in python3.8.8 (Windows 10) and im getting below error I have install Visual Studio Build Tools 2019 and reboot my PC Downgrade my Python from 3.9.5 to 3.8.8 C:\Program Files…

Append text to the last line of file with python

First, I use echo hello, >> a.txt to create a new file with one line looks like that. And I know \n is at the last of the line.Then I get some data from python, for example "world", I w…

Python Caesar Cipher [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 2…

Indent Expected? [duplicate]

This question already has answers here:Im getting an IndentationError (or a TabError). How do I fix it?(6 answers)Closed 7 months ago.Im sort of new to python and working on a small text adventure its…

Convert QueryDict to key-value pair dictionary

I have a QueryDict that I get from request.POST in this format: <QueryDict: {name: [John], urls: [google.com/\r\nbing.com/\r\naskjeeves.com/], user_email: [[email protected]]}>Why are the values …

How to test items with each other in 2 dimensional list?

We have a 2 dimensional list (for this example we have it populated with unique 6 nodes and 3 masks)myList = [[node1, mask1], [node2, mask1], [node3, mask1], [node4, mask2], [node5, mask2], [node6, mas…

InsecureRequestWarning + MarkupResemblesLocatorWarning:

Id like to scrape a site for my office work. I am learning each day. I need your support guys. Here is the Code: url = https://www.eprocure.gov.bd/partner/ViewTenderPaymentDetails.jsp?payId=33767442&a…