Python Numpy 数组从文本文件读取到二维数组

标签 python numpy

我有一个文本文件,其中包含以下内容:

-11.3815 -14.552 -15.7591 -18.5273 -14.6479 -12.7006 -13.9164 -19.8172 -22.951 -16.5832 
-16.555 -17.6044 -15.9577 -15.3363 -17.7223 -18.9881 -22.3789 -24.4881 -16.6685 -17.9475 
-18.2015 -15.2949 -15.5407 -18.8215 -24.5371 -17.0939 -15.3251 -13.1195 -13.3332 -19.3353 
-14.6149 -14.5243 -15.1842 -15.5911 -14.3217 -15.4211

里面有更多的数据。我想在二维数组中读取它。我尝试了以下方法:

with open('test.txt') as file:
     array2d = [[float(digit) for digit in line.strip()] for line in file]

而且似乎正在获得:

ValueError: could not convert string to float: -

知道如何解决这个问题吗?

最佳答案

你必须使用

split()

代替

strip()

因为 strip() 返回一个字符串,所以您要遍历该字符串的每个字符。 split() 返回一个列表,这就是您所需要的。在 Python docs 中阅读更多内容.

代码:

with open('sample.txt') as file:
    array2d = [[float(digit) for digit in line.split()] for line in file]

print array2d

输出:

[[-11.3815, -14.552, -15.7591, -18.5273, -14.6479, -12.7006, -13.9164, -19.8172, -22.951, -16.5832], [-16.555, -17.6044, -15.9577, -15.3363, -17.7223, -18.9881, -22.3789, -24.4881, -16.6685, -17.9475], [-18.2015, -15.2949, -15.5407, -18.8215, -24.5371, -17.0939, -15.3251, -13.1195, -13.3332, -19.3353], [-14.6149, -14.5243, -15.1842, -15.5911, -14.3217, -15.4211]]

关于Python Numpy 数组从文本文件读取到二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20928892/

相关文章:

Python Pandas——如果有条件则连接字符串

python - 无法从Python中的html页面中提取文本

Python:在 numpy 中定义矩阵的内存优化方式

python - 记录脚本适用于 python2 和 python3 以及特定的 matplotlib

python - 高效点积密集到稀疏

python - 迭代 NumPy 数组的列和另一个数组的元素?

python - 获取字符串中不同索引数量所需的快速方法

python - 使用python将目录中的所有文件重命名为每个文件中存在的行

python - Pandas csv 阅读器无法识别分隔符

python - python中多项式的唯一元素