2017-08-23 85 views
1

如果你有不同的字符串類型的多個numpy的陣列,如:通用字符串比較

In [411]: x1.dtype 
Out[411]: dtype('S3') 

In [412]: x2.dtype 
Out[412]: dtype('<U3') 

In [413]: x3.dtype 
Out[413]: dtype('>U5') 

有沒有辦法,我可以檢查它們是否所有字符串,而不必與每個比較任何方式個人類型明確?

例如,我願做

In [415]: x1.dtype == <something> 
Out[415]: True 

In [416]: x2.dtype == <something> # same as above 
Out[416]: True 

In [417]: x3.dtype == <something> # same as above 
Out[417]: True 

相較於str =沒有布埃諾:

In [410]: x3.dtype == str 
Out[410]: False 

回答

3

一種方法是使用np.issubdtypenp.character

np.issubdtype(your_array.dtype, np.character) 

例如:

>>> np.issubdtype('S3', np.character) 
True 

>>> np.issubdtype('<U3', np.character) 
True 

>>> np.issubdtype('>U5', np.character) 
True 

這是從NumPy文檔中提取的NumPy dtype層次結構(如圖像!)。如果要檢查常見的D型類這是非常有幫助的:

enter image description here

正如你可以看到np.str_np.unicode_都「繼承」 np.character

+1

這絕對是我需要的。謝謝。 –