简体   繁体   中英

Multiplying each digit in a number pandas

I'm working on a problem to help get better at coding in Python/Pandas and I'm stuck on this scenario.

这是用于更好描述的表

Step 1: Multiply each individual character by a given number.

Step 2: Add the results to create a sum.

Step 3: Subtract the sum from the nearest equal or higher multiple of ten.

I want to do this for numbers in a series. For example: Series=[123456789012],[02345434225],[2349349723]

Setup

df = pd.DataFrame([
    [6, 2, 9, 1, 0, 4, 1, 5, 0, 0, 2, 1],
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2]
]).add_prefix('N')

a = np.array([1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3])

Solution

  • Multiply by an array broadcast over rows
  • Sum over rows
  • Modulo 10
  • Assign to a new column

df.assign(Check=(df * -a).sum(1).mod(10))

   N0  N1  N2  N3  N4  N5  N6  N7  N8  N9  N10  N11  Check
0   6   2   9   1   0   4   1   5   0   0    2    1      3
1   1   2   3   4   5   6   7   8   9   0    1    2      8

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM