Home > Software engineering >  How to get the last digit in each row in a number series in pandas
How to get the last digit in each row in a number series in pandas

Time:09-02

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

CodePudding user response:

Let's do some math: (i.e. 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

CodePudding user response:

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
  • Related