【问题标题】:Reshaping after numpy loadtxt: cannot reshape array of size x into shape (x,y)在 numpy loadtxt 之后重塑:无法将大小为 x 的数组重塑为形状 (x,y)
【发布时间】:2017-10-07 23:13:14
【问题描述】:

我有以下文本文件,file.txt 有 3 行 4 列:

0.0 0.0 0.0
0.0 0.0 10.0
15 10 2001 2995

我正在使用 np.loadtxt 将其作为数组读取。 Loadtxt 将其作为一维数组读入,我想将其转换回其结构与文本文件中相同的 3x4 数组。我试过了

file = sys.argv[1] #I'm just reading it from the command line when executing the program
data = np.loadtxt(file, delimiter='\t', dtype = str)
print(data.shape, data)
data = data.reshape(3,4)

但收到以下错误:

(3,)
['0.0 0.0 0.0' '0.0 0.0 10.0' '15 10 2001 2995']
ValueError: cannot reshape array of size 3 into shape (3,4)

我已经编辑掉了形状和错误之间的不相关信息。如何将此文本文件重新整形为 3x4 数组?它不必通过加载文本。我也尝试过使用 np.genfromtxt 也无济于事。

【问题讨论】:

  • 你为什么要使用delimiter=',' 来处理一个没有, 分隔的文件?
  • 那你为什么断言输入结构是3x4?
  • 修复了分隔符。这就是我在文本编辑器中打开文件时的样子。
  • 在 `copy-n-paste 中,如果有标签,请不要通过。所以你的样本看起来就像'空白'分隔。前 2 行有 3 列,但最后有 4 列。因此出现错误。

标签: python file numpy


【解决方案1】:

您不需要reshape 数据,只需将loadtxt 函数中的分隔符从, 更改为空格' '

data = np.loadtxt(file, delimiter=' ', dtype = str)

这实际上会将您的数据加载为 3x4 字符串数组,其中缺少的元素显示为空字符串 ''。然后,您可以使用

将其替换为零
np.place(data, data == '', '0.0')

并使用以下方法转换为浮点数:

data = np.asarray(data, dtype = float)

【讨论】:

  • 不幸的是,这不是错误。我想这些只是空格。给我的文本文件那里没有值。我不确定如何在我的示例中正确添加这些内容。
  • 那么您的数据看起来如何?我的意思是,当我在 OP 中运行您的代码时,它给了我一个重塑错误,因为输入数组是一个 3 元素数组,每个元素都是您的示例输入的一行。
  • 是的,这一定是问题所在。抱歉,我对此有些陌生。正在寻找将该文本放入形状为 3,4 的 numpy 数组中。
【解决方案2】:

Pandas 擅长读取缺少条目的数据。如果你没有 pandas,你可以安装它:

pip install pandas

在此之后,您可以使用pd.read_table 来读取您的数据。缺失值替换为NaNs。

import pandas as pd
x = pd.read_table('data.txt', sep='\s+', 
            header=None, names=range(4)).values

print(x)
array([[    0.,     0.,     0.,    nan],
       [    0.,     0.,    10.,    nan],
       [   15.,    10.,  2001.,  2995.]])

【讨论】:

    猜你喜欢
    • 2019-09-27
    • 1970-01-01
    • 2020-10-15
    • 2019-08-23
    • 2020-02-18
    • 2020-04-14
    • 2020-10-05
    • 2020-01-09
    • 1970-01-01
    相关资源
    最近更新 更多