Create check digit function

2024/11/18 16:25:20

I'm trying to create check digits and append them after the original UPCs. Here's the sample data

Because there are leading 0's, I have to read the data as strings first:

import pandas as pd                                                                 
upc = pd.read_csv("/Users/lee/Desktop/upc.csv", dtype = str)

Here's an example of the check digit algorithm:
If upc is 003459409000
step (1) 0 + 3*0 + 3 + 3*4 + 5 + 3*9 + 4 + 3*0 + 9 + 3*0 + 0 + 3*0 = 60
step (2) 60 mod 10 = 0
step (3) check digit = 0 (if it's not 0, then check digit = 10 - number in step 2)

Based on the algorithm, here's the code:

def add_check_digit(upc_str):  upc_str = str(upc_str)if len(upc_str) != 12: raise Exception("Invalid length")odd_sum = 0even_sum = 0 for i, char in enumerate(upc_str): j = i+1 if j % 2 == 0: even_sum += int(char) else:odd_sum += int(char) total_sum = (even_sum * 3) + odd_sum mod = total_sum % 10 check_digit = 10 - mod if check_digit == 10: check_digit = 0 return upc_str + str(check_digit) 

If I run this code, it gives correct check digit and appends this result to the end of the original UPC. For the example above, if I type:

add_check_digit('003459409000')

The output gives 13-digit UPC 0034594090000.

Now my questions are:

  1. This function works only for a single upc, i.e., I have to copy/paste each single upc and get the check digit. How do I create a function that works for a list of UPSs in a dataframe? Each result should return a 13-digit UPC with the check digits appended after the original UPC.

  2. The UPCs are read as strings. How do I apply the function to the UPCs? I suppose I should convert the strings to numbers somehow.

  3. After I get the new UPCs, how do I save the result in a csv file?

Answer

data set up for me as I don't have CSV file, below step is the same as your

df = pd.read_csv("/Users/lee/Desktop/upc.csv", dtype = str)

data setup

import pandas as pd
df=pd.DataFrame({"upc_in_file":['003459409000','003459409001','003459409002']})
def add_check_digit(upc_str):  upc_str = str(upc_str)if len(upc_str) != 12: raise Exception("Invalid length")odd_sum = 0even_sum = 0 for i, char in enumerate(upc_str): j = i+1 if j % 2 == 0: even_sum += int(char) else:odd_sum += int(char) total_sum = (even_sum * 3) + odd_sum mod = total_sum % 10 check_digit = 10 - mod if check_digit == 10: check_digit = 0 return upc_str + str(check_digit) 

apply the above function to the upc column(the one which was read from file)

df['new_upc']=df['upc_in_file'].apply(add_check_digit)

now save the file!

df.to_csv("my_updated_upc.csv")

this will look like enter image description here

https://en.xdnf.cn/q/120057.html

Related Q&A

Getting count of permutations in a faster way

Using this code to get count of permutations is slow on big numbers as the partition part takes long time to calculate all the partitions for a number like 100 and because of all the partitions in the …

How to find number of vowels in each word of string? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to repro…

Python error: AttributeError: str object has no attribute read

My full code:import requests as req import json Bin = int(300000) BinMax = int(600000) File = open("C:/Users/admin/Desktop/PS Now Generaetors/Bins.txt", a)while bin != BinMax:json1 = req.get(…

list elements sum of one list first element to last element of second list

How to sum first element of one list to last element of second list if both list contains same amount of elements in python. Source code (should be kind of like this): def update(l1,l2,l3):for i in ran…

Append float data at the end of each line in a text file

I have a .txt file and Im trying to add float number at the end of each line with incremented value than the last line. This is what I have in the .txt file:>520.980000 172.900000 357.440000 >320…

Change and Sort list in list in specific order in python

Hello guys I have this type of data in list in list array = [ ["PRODUCT NAME PACK","BAIGAM KOT","FIAZ BAGH","OLD ANARKALI","SULTAN PURA","TEZAB AA…

How to interact with the reCAPTCHA Solve the challenge button using Selenium and Python

Im trying to interact with the recaptcha Solve the challenge button on image verification popup using Selenium and Python. The xpath looks correct in dev tools but using Selenium unable to interact wit…

How to convert an adjacency matrix to an adjacency list with python?

I have an adjacency matrix like: [[ 0., 15., 0., 7., 10., 0.],[ 15., 0., 9., 11., 0., 9.],[ 0., 9., 0., 0., 12., 7.],[ 7., 11., 0., 0., 8., 14.],[ 10., 0., 12., …

how to plot a box plot of a column of a data frame in two groups in matplotlib

I have the following data frame:value total_spend margin1 29493.14 10203.371 27551.22 19003.072 22881.26 15142.681 15254.77 12337.221 11873.95 9424.231 11382.89 8767.83…

Text manipulation to form an equation

a=0.77 ,b=0.2 ,c=0.20, d=0.79 ,z=(c+d), e=(z*a) ,output=(z+e) I have a text file like above. I need a parser logic that will throw an equation like output=(0.20+0.79)+((0.20+0.79)*a) what are some effi…