简体   繁体   English

将每个数字乘以一个熊猫

[英]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. 我正在研究一个问题,以帮助您更好地使用Python / Pandas进行编码,而我一直陷于这种情况。

这是用于更好描述的表

Step 1: Multiply each individual character by a given number. 步骤1:将每个单个字符乘以给定的数字。

Step 2: Add the results to create a sum. 步骤2:将结果相加即可得出总和。

Step 3: Subtract the sum from the nearest equal or higher multiple of ten. 步骤3:从10的最接近相等或更高倍数中减去总和。

I want to do this for numbers in a series. 我想对一系列数字进行此操作。 For example: Series=[123456789012],[02345434225],[2349349723] 例如: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 模数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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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