2017-08-04 69 views

回答

3

可以使用Series.map用词典:

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

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 
2

df.replace作品:

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

df.eq另一种可能性(不就地):

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

您还可以使用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 
+0

看看我的回答,如果你想新的东西LOL – Wen

1

我的解决办法是从哪里来的方式我R中实现它通过使用factor

在蟒蛇pandascategory

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 
+0

很不错的!学到了新东西。 +1 –

+0

@cᴏʟᴅsᴘᴇᴇᴅ,仅仅是来自R的一个窍门,在0.15只熊猫之后,熊猫也拥有它〜已经为你提供了upvoted – Wen