anon_swe
anon_swe

Reputation: 9355

Convert specific string values to specific numeric values in Pandas

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!

Upvotes: 0

Views: 488

Answers (3)

BENY
BENY

Reputation: 323396

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

Upvotes: 1

cs95
cs95

Reputation: 403258

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

Upvotes: 2

akuiper
akuiper

Reputation: 215137

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

Upvotes: 3

Related Questions