简体   繁体   English

如何在 pandas 中的数字系列中获取每一行的最后一位数字

[英]How to get the last digit in each row in a number series in pandas

I have a data frame that contains many data.我有一个包含许多数据的数据框。 One column named 'x' (the most relevant), contains numbers and I want to get just the last digit to then operate if it meets the condition.一列名为“x”(最相关)包含数字,如果满足条件,我只想获取最后一个数字然后进行操作。

df = pd.DataFrame({'value':[500, 200, 100],
                   'x':[125, 129, 349]})

   value    x
0    500  125
1    200  129
2    100  349

Once having the data frame, I want to check if the last digit inside the value 'x' is 5 and if so then multiply by 2 the column 'value' and if not, don't do any operation.拥有数据框后,我想检查值“x”内的最后一位数字是否为 5,如果是,则将“值”列乘以 2,如果不是,则不要执行任何操作。 The end result should be:最终结果应该是:

df2 = pd.DataFrame({'value':[500, 200, 100],
                    'x':[125, 129, 349],
                    'value2':[1000, 200, 100]})

   value    x  value2
0    500  125    1000
1    200  129     200
2    100  349     100

Let's do some math: (ie if the number ends with 5 then the modulo division by 10 will always yield 5 )让我们做一些数学运算:(即如果数字以 5 结尾,那么模除以10将始终产生5

df['value2'] = df['value'].mask(df['x'] % 10 == 5, df['value'] * 2)

   value    x  value2
0    500  125    1000
1    200  129     200
2    100  349     100

To check if an integer ends with 5, we can look at its mod 10 value, then use np.where to choose conditions.要检查 integer 是否以 5 结尾,我们可以查看它的 mod 10 值,然后使用np.where选择条件。

df['value2'] = np.where(df.x.mod(10).eq(5), df.value.mul(2), df.value)
print(df)

Output: Output:

   value    x  value2
0    500  125    1000
1    200  129     200
2    100  349     100

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

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