Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rename values in a column using pandas or if/then

I have the below dataset and would like to rename 1 to Sold, 2 to Sold, and nan to Unsold

DF

Status
1
2
nan

Desired DF

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Status
Sold
Sold
Unsold

I am currently using the replace function but doing each condition separately. Is there a way to do it all at the same time?

df['Status'] = df['Status'].str.replace['1', 'Sold']

>Solution :

use map with a dictionary:

df['Status'] = df['Status'].map({'1': 'Solde', '2': 'Solde', np.nan: 'Unsold'})

NB. If NaNs are strings:

df['Status'] = df['Status'].map({'1': 'Solde', '2': 'Solde', 'nan': 'Unsold'})

Or, if you only have 1/2 -> Sold ; nan -> Unsold:

# if real NaN
df['Status'] = np.where(df['Status'].notna(), 'Sold', 'Unsold')

# if string
df['Status'] = np.where(df['Status'].ne('nan'), 'Sold', 'Unsold')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading