【问题标题】:Convert and check array datatype转换和检查数组数据类型
【发布时间】:2017-05-09 11:35:15
【问题描述】:

对于 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))

提前致谢!

【问题讨论】:

  • 你能修复一下缩进吗?
  • 嗨,我猜你误解了np.all 的工作原理。如果数组的所有元素都是True,它给出True,否则给出False。这里00.0 被认为是False,所有其他数字被认为是True。您的比较仅检查两个数组是否包含零。您需要将条件更改为numpy.all(x==x_float32)。此外,您只想检查函数调用中给出的数据类型。 Atm 你只检查float32,如果这有效,给True end 继续检查elseway。

标签: python arrays numpy type-conversion


【解决方案1】:

这适合你吗?

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 进行比较。

【讨论】:

  • @Naugeux 谢谢!堆栈溢出太棒了哈哈。从来没有这么快的回复
  • 快速回复取决于问题;) 随时将您的问题标记为已回答
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-30
相关资源
最近更新 更多