1

I need to add new columns Label with labels which are dependent on values of another column value.

i.e. if value < -50 so label "Critical" and if it between -50&-40 so it will "Major" and if it between -40&-30 so it will "Standard" and if it >-30 so it will "Normal"

My code is not working

X['Label'][X['Value']>=-30]="Normal"
X['Label'][X['Value']<-30][X['RSLDEV']>=-40]='Standard'
X['Label'][X['Value']<-40][X['RSLDEV']>=-50]="Major"
X['Label'][X['Value']<-50]="Critical"

Note: I don't need to use for loop

Output shall be as following:

Values  Label
-52.13446   Critical
-49.782227  Major
-46.363266  Major
-45.591278  Major
-45.591278  Major
-44.51123   Major
-42.430695  Major
-40.330933  Major
-35.779465  Standard
-35.779465  Standard
-29.621201  Normal

It failed with for loop :

X['Label']='Normal'
for x in range(len(X['Value'])):
    if X['Value'].iloc[x] >=-6 and X['Value'].iloc[x] <-3:
        X['Label']='Standard'
    elif X['Value'].iloc[x] >=-12 and X['Value'].iloc[x] <-6:
        X['RSLDEVD']='Major'
    elif X['Value'].iloc[x] <-12:
        X['RSLDEVD']='Critical'
    else:
        pass

1 Answer 1

1

you can use lambda to create your function and then apply it to your desired column in the dataframe, see below:

import pandas as pd
d = {'Value':[-55, -45, -35, -25]}
df = pd.DataFrame(data = d)

df['Label'] = df.Value.apply(lambda x: "Critical" if x <= -50 else ( "Major"  if x < -40 and x >= -50 else ("Standard" if x < -30 and x >= -40 else "Normal")))

print(df)
   Value     Label
0    -55  Critical
1    -45     Major
2    -35  Standard
3    -25    Normal
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you so much but why didn't work by for loop for x in range(len(X['Value'])): if X['Value'].iloc[x] >=-6 and X['Value'].iloc[x] <-3: X['Label']='Standard' elif X['Value'].iloc[x] >=-12 and X['Value'].iloc[x] <-6: X['Label']='Major' elif X['Value'].iloc[x] <-12: X['Label']='Critical' else: pass
Put your code as a formatted code and what is the error you get if any and i can look into it, with its current state i can’t tell what is it doing.
how can i do that?
Edit your original post! In the options while editing your post you can select any part of your post and change it to code. Alternatively, each line of code should begin with 4 spaces. You also need to put a sample of how your current dataframe look like.
i did ,thanks for your help to write regarding how to add code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.