python - 删除 numpy 数组末尾的 dtype

标签 python arrays numpy

我正在编写一种从数据文件创建数组的方法。该方法如下所示:

import numpy
def readDataFile(fileName):
    try:
        with open(fileName, 'r') as inputs:
            data = None
            for line in inputs:
                line = line.strip()
                items = line.split('\t')
                if data == None:
                    data = numpy.array(items[0:len(items)]) 
                else:
                    data = numpy.vstack((data, items[0:len(items)]))
                return numpy.array(data)
    except IOError as ioerr:
        print 'IOError: ', ioerr
        return None

我的数据文件包含几行数字,每一行之间用制表符分隔,例如:

1 2 3
4 5 6
7 8 9

我希望收到如下数组:

array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

但是,结果的末尾包含 dtype:

array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]], dtype='|S9')

因此,我无法对结果执行某些操作,例如如果我尝试使用 result.max(0) 查找每一行的最大值,我将收到一个错误:

TypeError: cannot perform reduce with flexible type.

那么,谁能告诉我我的代码有什么问题以及如何修复它?非常感谢。

最佳答案

Numpy 数组包含一个方法来完成这项工作:

import numpy as np
a = np.array(['A', 'B'])
a
# Returns: array(['A', 'B'],  dtype='|S1')

a.tolist()
# Returns ['A', 'B']

http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.tolist.html#numpy.ndarray.tolist

关于python - 删除 numpy 数组末尾的 dtype,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10288757/

相关文章:

php - Laravel Eloquent PostgreSQL 保存数组错误: preg_replace(): Parameter mismatch

编译错误 : sizeof() operator in C

python - Pandas DataFrame上的NaN替换引发TypeError:找不到匹配的签名

表示为元组的树的 python 比较

python - 模拟在 Python 2.7 中访问时引发异常的可订阅属性的正确方法是什么?

python - 从没有全局变量的其他包访问非返回函数内的变量

python - Numpy 已安装但仍然出现错误

python - Django - 如何将 user_pass_test 与 url 一起使用

arrays - 如何使用 VALUES 接受数组到 CTE,然后作为单独的记录插入

python - 如何使用 Numpy 更快地最小化这个距离? (找到两个信号彼此接近的移位索引)