簡體   English   中英

如何將所有字符串(如“故障”)轉換為唯一的浮點數?

[英]How do I convert all strings (like “Fault”) and into a unique float?

我有一個DataFrame,其中包含intfloatobject (帶字符的字符串)項。 我希望每個獨特的物體都有一個獨特的浮子,如此

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM