jeudi 7 mai 2020

add column values according to value with if

I would like to create following dataframe:

Desired Dataframe

df = pd.DataFrame({
    'A': ['0','0','0','8.020833015','8.009259224','8.003472328','8.020833015','0','0','5','4.994213104','0','0','0','8.012152672','8.009259224','0'],
    'Step_ID': ['Step_1','Step_1','Step_1','Step_2','Step_2','Step_2','Step_2','Step_3','Step_3','Step_4','Step_4','Step_5','Step_5','Step_5','Step_6','Step_6','Step_7']})
print (df)

What I have is the column A and according to these values I would like to set the values in the column Step_ID.

Step_ID - it begins from Step_1. Then if the number is bigger then Step_2 (for all the number that are bigger than 0, till the zero values will be reached). Then to zero values should be Step_3 assigned and so on.

# add a Step ID
df = pd.DataFrame({
    'A': ['0','0','0','8.020833015','8.009259224','8.003472328','8.020833015','0','0','5','4.994213104','0','0','0','8.012152672','8.009259224','0']})
step = 0
value = None
def get_step(x):
    global step
    global value
    if x != value:
        value = x
        step += 1
    return f'Step_{step}'
df['Step_ID'] = df['A'].apply(get_step)
df.to_csv('test.csv' , index=None)

The code above does something similar, but only with unique numbers. Should be there one more "if" - if value > 0 in order to perform desired functionality?

Aucun commentaire:

Enregistrer un commentaire