将一行零添加到数组而不是我想要的行

时间:2013-01-17 02:37:16

标签: python arrays

我有一个数组,我正在做一些计算。数组以

开头
e = array([[1,2,1,3],
           [3,-1,-3,-1],
           [2,3,1,4]])

我稍微修改它以将其转换为:

array([[  1,   2,   1,   3],
      [  0,  -7,  -6, -10],
      [  0,  -1,  -1,  -2]])

然后我在其上运行此代码:

import numpy as np
from fractions import Fraction

def ref(x):
    dimension = x.shape
    row_counter = 1
    first_values = [x[i][row_counter] for i in range(dimension[0])]                               #gets a list of elements of the column
    first_values = [number != 0 for number in first_values]                                       #0 is a pivot element?
    if False in first_values:                                                                     
        true_index =  first_values.index(True); false_index =   first_values.index(False)
        if true_index > false_index:                                                               #not any more
            x[[false_index, true_index]] = x[[true_index, false_index]]

    for i in range(row_counter+1,dimension[0]):
        multiplier = Fraction(x[row_counter][row_counter], x[i][row_counter])**-1
        row1 = multiplier*x[row_counter]
        row1 = x[i]-row1
        print row1
        x[i] = row1   

return x

运行此命令返回:

[0 0 -1/7 -4/7]
array([[  1,   2,   1,   3],
         [  0,  -7,  -6, -10],
         [  0,   0,   0,   0]])

所以结果应该是

array([[  1,   2,   1,   3],
         [  0,  -7,  -6, -10],
         [  0, 0, -1/7, -4/7]])

它打印正确的行条目但不会添加到数组中,而是添加一行零。有人可以告诉我为什么吗?感谢。

1 个答案:

答案 0 :(得分:2)

通常,numpy数组是特定类型的同类数组。例如:

>>> a = np.array([1,2,3])
>>> a
array([1, 2, 3])
>>> a.dtype
dtype('int64')

当你专门设置一个元素或切片时,你添加的内容会被强制转换为当前的dtype,所以:

>>> a[0] = 5
>>> a
array([5, 2, 3])

>>> a[0] = 4.3
>>> a
array([4, 2, 3])

当你没有就地行动时,你可以得到升级,所以numpy无论如何都要制作副本(即新对象):

>>> a = np.array([1,2,3])
>>> a + 4.3
array([ 5.3,  6.3,  7.3])
>>> (a + 4.3).dtype
dtype('float64')

在您的情况下,如果您使用numpy dtype object数组开头,则可以获得所需的行为:

>>> e = np.array([[  1,   2,   1,   3],
...               [  0,  -7,  -6, -10],
...               [  0,  -1,  -1,  -2]], dtype=object)
>>> 
>>> ref(e)
array([[1, 2, 1, 3],
       [0, -7, -6, -10],
       [0, 0, -1/7, -4/7]], dtype=object)
相关问题