![](/img/trans.png)
[英]In pandas, how do I convert a series of float or none to strings with integers
[英]How do I convert all strings (like “Fault”) and into a unique float?
我有一個DataFrame,其中包含int
, float
和object
(帶字符的字符串)項。 我希望每個獨特的物體都有一個獨特的浮子,如此
Exhuast
Fault
Probation
Exhaust
Fault
Motor
至
1.
2.
3.
1.
2.
4.
此外,它是否適用於所有列,還是我必須逐列?
最后一個問題,它還將所有的int
轉換為float
嗎?
正如Jon所說,你可以使用Series.factorize
。
(s.factorize()[0]+1).astype('float')
要在整個DataFrame上按列執行此操作,只需使用apply
。
演示
>>> s = pd.Series(['Exhaust', 'Fault', 'Probation', 5, int,
'Exhaust', int, 'Fault', 'Motor'])
>>> s
0 Exhaust
1 Fault
2 Probation
3 5
4 <class 'int'>
5 Exhaust
6 <class 'int'>
7 Fault
8 Motor
dtype: object
>>> (s.factorize()[0]+1).astype('float')
array([ 1., 2., 3., 4., 5., 1., 5., 2., 6.])
甲NumPy的解決方案可以是使用return_inverse
的關鍵字ARG np.unique
,
(np.unique(s, return_inverse=True)[1]+1).astype('float')
然而,從一些粗略的基准測試來看,Pandas解決方案可能會更快。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.