简体   繁体   中英

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.

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. 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 )

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.

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

Output:

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

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