我有一个名为df
的Pandas数据框,其中包含_type
列,其中包含First
或Second
。我想将所有First
值转换为1,并将所有Second
值转换为2.将特定的字符串值转换为Pandas中的特定数值
我应该如何处理这个问题?
谢谢!
我有一个名为df
的Pandas数据框,其中包含_type
列,其中包含First
或Second
。我想将所有First
值转换为1,并将所有Second
值转换为2.将特定的字符串值转换为Pandas中的特定数值
我应该如何处理这个问题?
谢谢!
可以使用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
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
我的解决办法是从哪里来的方式我R中实现它通过使用factor
。
在蟒蛇pandas
应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
很不错的!学到了新东西。 +1 –
@cᴏʟᴅsᴘᴇᴇᴅ,仅仅是来自R的一个窍门,在0.15只熊猫之后,熊猫也拥有它〜已经为你提供了upvoted – Wen
看看我的回答,如果你想新的东西LOL – Wen