【问题标题】:Numpy Array Concatenation Multiplies array... why?Numpy Array Concatenation 将数组相乘...为什么?
【发布时间】:2017-06-07 17:09:05
【问题描述】:

我一直在拼命想弄清楚为什么数组连接会导致数组在第一次迭代时被乘以 2...

这是我的代码:

def run(filename, max_iter = 1e6):
    data, fm = data_extraction(filename)

    large_output = None

    iteration_count = 0    

    while iteration_count < max_iter:
        iteration_count += 1
        print iteration_count
        results = calculations(data, (0.9,1.1))

        if large_output == None:
            large_output = results[:,1] #stores the energy array
            print large_output
        else:
            large_output = np.c_[ large_output, results[:,1]]
            #large_output = np.vstack([large_output, power_and_energy_var[:,1]])
            print large_output

这是打印语句和 3 次迭代的控制台输出:

1
[  3.59891391e+01   5.75841568e+00   ]
2
[[  7.22402719e+01   3.62511328e+01]
 [  1.16726670e+01   5.91425129e+00]]
3
[[  7.22402719e+01   3.62511328e+01   3.70141435e+01]
 [  1.16726670e+01   5.91425129e+00   6.02176042e+00]]

如您所见,7.22402719e+01 大约是 3.59891391e+01 的两倍,但在连续迭代中不会发生...

我不知道为什么会这样。我已经尝试了所有我能想到的:

1) 使用打印语句检查正在执行的具体内容 2)重新加载内核以擦除任何挥之不去的变量 3) 使用 np.vstack 而不是 np.c_ (同样的错误)

非常欢迎任何帮助!

【问题讨论】:

  • large_output = results[:,1] 正在查看results 的一部分。如果它正在查看的数组发生更改,则视图将反映这些更改。连接(虽然很慢,而且是个坏主意)可能与您的问题无关。
  • large_outputresults[:,1] 在第一次迭代时不是空的吗?输出表明堆叠的数组在那里是一维的,而连续的则是二维的。
  • @Divakar : no large_output 在第一次迭代期间被填满,因为它是 None。并且结果不为空。
  • @user2357112 :我不确定我是否理解您评论的第一部分抱歉。你介意再解释一遍吗?你会建议什么替代串联?
  • Here's a quick intro to views and copies,至于连接,适当的决定将取决于您的代码实际在做什么。

标签: python arrays numpy concatenation


【解决方案1】:

使用简单的results 数组复制您的串联:

In [229]: results = np.arange(12).reshape(2,6)
In [230]: out = results[:,1]
In [231]: out = np.c_[out, results[:,2]]
In [232]: out = np.c_[out, results[:,3]]
In [233]: out
Out[233]: 
array([[1, 2, 3],
       [7, 8, 9]])

即使最初的 out 是 1d,后续的只是连接列

In [234]: results[:,1]
Out[234]: array([1, 7])

因此,cnt 1 和 2 之间的任何有趣业务都是 datacalculations 中未知行为的结果。 np.c_ 连接没有问题。

也就是说,先建立列表的建议很好

In [237]: out = []
In [238]: out.append(results[:,1])
In [239]: out.append(results[:,2])
In [240]: out.append(results[:,3])
In [241]: out
Out[241]: [array([1, 7]), array([2, 8]), array([3, 9])]
In [242]: np.array(out)
Out[242]: 
array([[1, 7],
       [2, 8],
       [3, 9]])

虽然它可能不会绕过任何有趣的事情来创建results

【讨论】:

    【解决方案2】:

    尽管在 cmets and answers 中提出了所有非常好的 cmets 和建议,但答案比这简单得多(通常是我花了很长时间在电脑上敲脑袋的时候)。

    large_output = results[:,1]

    应该明确表示为数组:

    large_output = np.array(results[:,1])

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-04
      • 2014-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多