显示数组内元素的数据类型并将其转换为整数。 Python 和 Numpy

Show the data type of elements inside the array and convert it to Integer. Python and Numpy

所以我正在努力解决作业中的一个问题。我们得到包含几百个元素的 txt 文件,我们需要显示数组自行车(文本文件)中元素的数据类型并将其转换为整数。

我试过了

print(type(bike))
bike.astype(int)

并获得

<class 'numpy.ndarray'>
array([ 985,  801, 1349, 1562, 1600, 1606, 1510,  959,  822, 1321, 1263,
       1162, 1406, 1421, 1248, 1204, 1000,  683, 1650, 1927, 1543,  981,
        986, 1416, 1985,  506,  431, 1167, 1098, 1096, 1501, 1360, 1526,
       1550, 1708, 1005, 1623, 1712, 1530, 1605, 1538, 1746, 1472, 1589,
       1913, 1815, 2115, 2475, 2927, 1635, 1812, 1107, 1450, 1917, 1807,
       1461, 1969, 2402, 1446, 1851, 2134, 1685, 1944, 2077,  605, 1872,
       2133, 1891,  623, 1977, 2132, 2417, 2046, 2056, 2192, 2744, 3239,
       311, ...])

上面的点表示还有很多数据

我期待我的尝试,return 'Int' 或 运行 bike.astype(int)

之后的类似内容

您可以使用 numpy 数组的 .dtype 属性

bike.dtype

结果(转换为整数后)

dtype('int64')

如果你想获取文本文件中的内容并将它们转换为整数值,你可以使用 ord() 函数,如果你想获取它们的数据类型,你可以使用 type() 函数。

ord()函数returns表示指定字符的unicode编码的数字。

示例代码:

f = open('text.txt', 'r')
contents = f.read()
dtype_and_int_values = [[type(item), ord(item)] for item in contents]
print(dtype_and_int_values)