0

I have a Pandas dataframe called df with a _type column, containing either First or Second. I'd like to convert all First values to 1 and all Second values to 2.

How should I go about this?

Thanks!

3 Answers 3

3

You can use Series.map with a dictionary:

df['_type'] = df['_type'].map({'First': 1, 'Second': 2})

Example:

df = pd.DataFrame({
        '_type': ['First', 'Second', 'First', 'Second']
    })

df
#   _type
#0  First
#1  Second
#2  First
#3  Second

df['_type'] = df['_type'].map({'First': 1, 'Second': 2})

df
# _type
#0  1
#1  2
#2  1
#3  2
Sign up to request clarification or add additional context in comments.

Comments

2

df.replace works:

In [10]: df._type.replace(('First', 'Second'), (1, 2), inplace=True); df
Out[10]: 
   _type
0      1
1      2
2      1
3      2 

Another possibility with df.eq (not inplace):

In [15]: df._type.eq('Second').mul(1) + 1 
Out[15]: 
0    1
1    2
2    1
3    2
Name: _type, dtype: int64

You can also use np.where:

In [28]: pd.Series(np.where(df._type == 'First', 1, 2)).to_frame('_type')
Out[28]: 
   _type
0      1
1      2
2      1
3      2

1 Comment

Look at my answer, If you want something new LOL
1

My solution is come from way i achieve it in R by using factor.

In python pandas should be category

df = pd.DataFrame({'_type': ['First', 'Second', 'First', 'Second']})
df['_type'].astype('category').cat.codes.add(1)  


Out[706]: 
0    1
1    2
2    1
3    2
dtype: int8

2 Comments

Very nice! Learned something new. +1
@cᴏʟᴅsᴘᴇᴇᴅ, just a trick from R , after 0.15 pandas , pandas have it too~ already upvoted for u

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.