[英]numpy convert array of strings to integers or boolean (for masking)
我是Python的新手,我面臨着將字符串數組轉換為數字的挑戰。 我的數據是從更大的數字和字符串數據集中提取的。 看起來像:
array([b'Single', b'', b'', b'', b'', b'Single', b'Single',
b'', b'Single', ...])
我想用這個數據創建一個掩碼,基本上如果'Single'存在我想要一個False或0,這樣我就可以屏蔽原始數據集了。 我不知道為什么那里有b。
我發現類似的問題已經回答,但不是字符串到數字或字符串到布爾值,只是反向或將“數字串”轉換為整數。
我最接近的解決方案是這樣的:
np.where(modMask = 'Single' [False, True])
但后來我得到了錯誤:
TypeError Traceback (most recent call last)
<ipython-input-64-4ad8a8f10b9b> in <module>()
----> 1 np.where(modMask = 'Single' [False, True])
TypeError: string indices must be integers
你可以使用numpy.vectorize
import numpy as np
def f(x):
return not x == b'Single'
vfunc = np.vectorize(f)
x = np.array([b'Single', b'', b'', b'', b'', b'Single'])
result = vfunc(x)
哪里
result = [False True True True True False]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.