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
| 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')