【问题标题】:How can I make a 2-D Array in Python from a .txt file?如何从 .t​​xt 文件在 Python 中创建二维数组?
【发布时间】:2015-07-16 04:03:50
【问题描述】:

我必须将一个包含 9 列和 807022 行的 .txt 文件导入到我的程序中,以便对它进行排序。我已经尝试了代码:

with open('ExampleTable.txt') as file:
    array2d = [[float(digit) for digit in line.split()] for line in file]
f = Find_StDev(Find12EpochStars(array2d), array2d)
print (f)

但是,我收到错误消息: ValueError:无法将字符串转换为浮点数:'%'

文本文件是浮点数和整数。

如何导入 .txt 文件以便函数使用它?

【问题讨论】:

  • 在从文件中读取时,可以确定这些值是作为字符串读取的。您可以使用map() 将它们转换为浮点数
  • 您确定您的文件中没有符号 % 吗?首先检查。如果你的文件已经有行和列,array2d = numpy.loadtxt('ExampleTable.txt') 可能是你的朋友。
  • 您可能会看到该文件包含floats 和ints,但解释器在其中一列中看到% 符号并且不知道如何处理它,因为这不是一个数字。
  • 是的,谢谢,5000 万个数字中只有 1 个“%”
  • 如果你有这么多的数据,使用 numpy 会让事情变得更快,并且它有很好的功能从文本文件中读取数组docs.scipy.org/doc/numpy/reference/generated/…

标签: python text multidimensional-array import


【解决方案1】:

如果您以后想注意这一点,可以添加一个快速检查以确保首先可以进行转换。

对于数以百万计的数字,如果一个值已损坏,这不应该过多地改变答案!

with open('ExampleTable.txt') as file:
    array2d = [[float(digit) for digit in line.split() if digit.isnumeric() else 0]
               for line in file]
    f = Find_StDev(Find12EpochStars(array2d), array2d)
    print (f)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 2012-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-04
    相关资源
    最近更新 更多