Home > OS >  Finding out if values in dataframe increases in tens place
Finding out if values in dataframe increases in tens place

Time:06-20

I'm trying to figure out if the value in my dataframe is increasing in the tens/hundreds place. For example I created a dataframe with a few values, I duplicate the values and shifted them and now i'm able to compare them. But how do i code and find out if the tens place is increasing or if it just increasing by a little, for example 0.02 points.

import pandas as pd  
import numpy as np

data = {'value':['9','10','19','22','31']}
df = pd.DataFrame(data)

df['value_copy'] = df['value'].shift(1)
df['Increase'] = np.where(df['value']<df['value_copy'],1,0) 

output should be in this case: [nan,1,0,1,1]

CodePudding user response:

IIUC, divide by 10, get the floor, then compare the successive values (diff(1)) to see if the difference is exactly 1:

np.floor(df['value'].astype(float).div(10)).diff(1).eq(1).astype(int)

If you want a jump to at least the next tens (or more) use ge (≥):

np.floor(df['value'].astype(float).div(10)).diff(1).ge(1).astype(int)

output:

0    0
1    1
2    0
3    1
4    1
Name: value, dtype: int64

NB. if you insist on the NaN:

s = np.floor(df['value'].astype(float).div(10)).diff(1)
s.eq(1).astype(int).mask(s.isna())

output:

0    NaN
1    1.0
2    0.0
3    1.0
4    1.0
Name: value, dtype: float64
  • Related