0

How can I replace certain values in df, column class that have "Np" value with index values in order to do some treatment. df

    class      Project 
  0  A1         Math
  1  A2         Physics
  2  Np         Music
  3  A3         Danse
  4  Np         Acting

So i used

df['class'] = df['class'].where(df['class'] != 'Np', df.index.to_series())

and i got what i wanted

df
  class  Project
0    A1     Math
1    A2  Physics
2     2    Music
3    A3    Danse
4     4   Acting

Then I want to remove the index and keep the field empty after i finish df analysis. Final output:

class  Project
0    A1     Math
1    A2  Physics
2         Music
3    A3    Danse
4        Acting

Is there a way to do this?

1 Answer 1

1

Save your initial test as a mask and reuse it later:

mask = df['class'] == 'Np'
df['class'] = df['class'].where(~mask, df.index.to_series())

# processing goes here

df['class'] = df['class'].where(~mask, '')

output:

   class    Project
0   A1      Math
1   A2      Physics
2           Music
3   A3      Danse
4           Acting
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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