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!
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
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
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