2017-05-09 26 views
0

對於Python課程,我希望得到你的幫助。轉換和檢查數組數據類型

定義一個函數check_conversion,它將兩個參數作爲輸入:一個數組和一個數據類型。該函數應返回一個布爾值,指示初始數組中的所有元素是否可以無損地轉換爲指定的數據類型。

現在我已經得到了這段代碼,但是它在每個輸入上都返回True。我們只能使用numpy庫,這是一個約束。 我可能會反思這一點,並會有一個更簡單的解決方案。

import numpy 
def check_conversion(x, d_type): 


x = numpy.array([x], dtype= d_type) 
dtype = "" 

x_float32 = x.astype('float32') 
x_float64 = x.astype('float64') 
x_int = x.astype('int') 
x_un_int64 = x.astype('uint64') 

print(x, x.dtype) 
print(x_int, x_int.astype) 
print(x_float32, x_float32.dtype) 


if numpy.all(x) == numpy.all(x_float32): 
    return True 


elif numpy.all(x) == numpy.all(x_float64): 
    return True 


elif numpy.all(x) == numpy.all(x_int): 
    return True 


elif numpy.all(x) == numpy.all(x_un_int64): 
    return True 

else: 
    return False 

a = numpy.array([3., 3.2, 1]) 
data_type_a = "int" 
print(check_conversion(a, data_type_a)) 
b = numpy.array([3., 3.2, -1]) 
data_type_b = "float32" 
print(check_conversion(b, data_type_b)) 
c = numpy.array([3., 3.2, -1]) 
data_type_c = "float64" 
print(check_conversion(c, data_type_c)) 
d = numpy.array([3, 2, -1]) 
data_type_d = "uint64" 
print(check_conversion(d, data_type_d)) 

在此先感謝!

+0

請問您能修好縮進嗎? – Nuageux

+0

嗨,我想你誤解了'np.all'是如何工作的。如果一個數組的所有元素都是「True」和「False」,它會給出「True」。這裏'0'和'0.0'被認爲是'假',其他所有數字都被認爲是'真'。您的比較只檢查兩個數組是否包含零。你需要改變你的條件爲'numpy.all(x == x_float32)'。你也只想檢查函數調用中給出的數據類型。 Atm你只檢查float32,如果這是工作,給'真正的'結束繼續檢查其他方式。 – jotasi

回答

0

這是否適合您?

import numpy 

def check_conversion(x, d_type): 
    xb = numpy.array(x, dtype= d_type) 
    print x, xb 
    if numpy.array_equal(x, xb): 
     return d_type, True 
    return d_type, False 

a = numpy.array([3., 3.2, 1]) 
data_type_a = "int" 
print(check_conversion(a, data_type_a)) 
b = numpy.array([3., 3.2, -1]) 
data_type_b = "float32" 
print(check_conversion(b, data_type_b)) 
c = numpy.array([3., 3.2, -1]) 
data_type_c = "float64" 
print(check_conversion(c, data_type_c)) 
d = numpy.array([3, 2, -1]) 
data_type_d = "uint64" 
print(check_conversion(d, data_type_d)) 

輸出

[ 3. 3.2 1. ] [3 3 1] 
('int', False) 
[ 3. 3.2 -1. ] [ 3.   3.20000005 -1.  ] 
('float32', False) 
[ 3. 3.2 -1. ] [ 3. 3.2 -1. ] 
('float64', True) 
[ 3 2 -1] [     3     2 18446744073709551615] 
('uint64', False) 

我創建一個新的xb陣列比我比較以前xnumpy.array_equal function

+0

@Naugeux謝謝!堆棧溢出真棒哈哈。從來沒有這樣的快速回復 – gerlof92

+0

快速回復取決於問題;)隨意標記你的問題爲答案 – Nuageux