numpy数组上的操作包含不同大小的行

时间:2021-07-06 12:08:10

I have two lists, looking like this:

我有两个列表,看起来像这样:

a= [[1,2,3,4], [2,3,4,5],[3,4,5,6,7]], b= [[5,6,7,8], [9,1,2,3], [4,5,6,7,8]]

which I want to subtract from each other element by element for an Output like this:

我想逐个元素地逐个减去输出,如下所示:

a-b= [[-4,-4,-4,-4],[7,2,2,2],[-1,-1,-1,-1,-1]]

In order to do so I convert each of a and b to arrays and subtract them I use:

为此,我将a和b中的每一个转换为数组并减去它们使用:

np.array(a)-np.array(b)

The Output just gives me the error:

输出只是给我错误:

Unsupported Operand type for-: 'list' and 'list'

不支持的操作数类型 - :'list'和'list'

What am I doing wrong? Shouldn't the np.array command ensure the conversion to the array?

我究竟做错了什么? np.array命令不应该确保转换到数组吗?

7 个解决方案

#1


1  

You can try:

你可以试试:

>>> a= [[1,2,3,4], [2,3,4,5],[3,4,5,6,7]]
>>> b= [[5,6,7,8], [9,1,2,3], [4,5,6,7,8]]
>>> 
>>> c =[]
>>> for i in range(len(a)):
    c.append([A - B for A, B in zip(a[i], b[i])])


>>> print c
[[-4, -4, -4, -4], [-7, 2, 2, 2], [-1, -1, -1, -1, -1]]

Or 2nd method is using map:

或者第二种方法是使用map:

from operator import sub
a= [[1,2,3,4], [2,3,4,5],[3,4,5,6,7]]
b= [[5,6,7,8], [9,1,2,3], [4,5,6,7,8]]
c =[]
for i in range(len(a)):
    c.append(map(sub, a[i], b[i]))  
print c
[[-4, -4, -4, -4], [-7, 2, 2, 2], [-1, -1, -1, -1, -1]]

#2


5  

Here is a Numpythonic way:

这是一种Numpythonic方式:

>>> y = map(len, a)  
>>> a = np.hstack(np.array(a))
>>> b = np.hstack(np.array(b))
>>> np.split(a-b, np.cumsum(y))
[array([-4, -4, -4, -4]), array([-7,  2,  2,  2]), array([-1, -1, -1, -1, -1]), array([], dtype=float64)]
>>> 

Since you cannot subtract the arrays with different shapes, you can flatten your arrays using np.hstack() then subtract your flattened arrays then reshape based on the previous shape.

由于无法减去具有不同形状的数组,因此可以使用np.hstack()展平数组,然后减去展平的数组,然后根据以前的形状重新整形。

#3


1  

The dimensions of your two arrays don't match, i.e. the first two sublists of a have 4 elements, but the third has 5 and ditto with b. If you convert the lists to numpy arrays, numpy silently gives you something like this:

两个数组的尺寸不匹配,即a的前两个子列表有4个元素,但第三个有5个,ditto有b。如果你将列表转换为numpy数组,numpy会默默地给你这样的东西:

In [346]: aa = np.array(a)
In [347]: bb = np.array(b)
In [348]: aa
Out[348]: array([[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6, 7]], dtype=object)
In [349]: bb
Out[349]: array([[5, 6, 7, 8], [9, 1, 2, 3], [4, 5, 6, 7, 8]], dtype=object)

You need to make sure that all your sublists have the same number of elements, then your code will work:

您需要确保所有子列表具有相同数量的元素,然后您的代码将起作用:

In [350]: a = [[1,2,3,4], [2,3,4,5],[3,4,5,6]]; b = [[5,6,7,8], [9,1,2,3], [4,5,6,7]] # I removed the last element of third sublist in a and b
In [351]: np.array(a) - np.array(b)
Out[351]: 
array([[-4, -4, -4, -4],
       [-7,  2,  2,  2],
       [-1, -1, -1, -1]])

#4


0  

Without NumPy:

没有NumPy:

result = []
for (m, n) in (zip(a, b)):
    result.append([i - j for i, j in zip(m, n)])

See also this question and this one.

另见这个问题和这个问题。

#5


0  

What about a custom function such as:

自定义功能怎么样,例如:

import numpy as np

a = [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6, 7]]
b = [[5, 6, 7, 8], [9, 1, 2, 3], [4, 5, 6, 7, 8]]


def np_substract(l1, l2):
    return np.array([np.array(l1[i]) - np.array(l2[i]) for i in range(len(l1))])

print np_substract(a, b)

#6


0  

You are getting the error, because your code is trying to subtract sublist from sublist, if you want to make it work, you can do the same in following manner:

您收到错误,因为您的代码试图从子列表中减去子列表,如果您想使其工作,您可以通过以下方式执行相同的操作:

import numpy as np
a= [[1,2,3,4], [2,3,4,5],[3,4,5,6,7]]
b= [[5,6,7,8], [9,1,2,3], [4,5,6,7,8]]

#You can apply different condition here, like (if (len(a) == len(b)), then only run the following code    
for each in range(len(a)):
    list = np.array(a[each])-np.array(b[each])
    #for converting the output array in to list
    subList[each] = list.tolist()

print subList

#7


0  

A nested list comprehension will do the job:

嵌套列表理解将完成这项工作:

In [102]: [[i2-j2 for i2,j2 in zip(i1,j1)] for i1,j1 in zip(a,b)] 
Out[102]: [[-4, -4, -4, -4], [-7, 2, 2, 2], [-1, -1, -1, -1, -1]]

The problem with np.array(a)-np.array(b) is that the sublists differ in length, so the resulting arrays are object type - arrays of lists

np.array(a)-np.array(b)的问题在于子列表的长度不同,因此生成的数组是对象类型 - 列表数组

In [104]: np.array(a)
Out[104]: array([[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6, 7]], dtype=object)

Subtraction is iterating over the outer array just fine, but hitting a problem when subtracting one sublist from another - hence the error message.

减法迭代在外部数组上很好,但是当从另一个子列表中减去一个子列表时遇到问题 - 因此出现错误消息。

If I made the inputs arrays of arrays, the subtraction will work

如果我创建了数组的输入数组,则减法将起作用

In [106]: np.array([np.array(a1) for a1 in a])
Out[106]: array([array([1, 2, 3, 4]), array([2, 3, 4, 5]), array([3, 4, 5, 6, 7])], dtype=object)

In [107]: aa=np.array([np.array(a1) for a1 in a])   
In [108]: bb=np.array([np.array(a1) for a1 in b])

In [109]: aa-bb
Out[109]: 
array([array([-4, -4, -4, -4]), 
       array([-7,  2,  2,  2]),
       array([-1, -1, -1, -1, -1])], dtype=object)

You can't count of array operations working on object dtype arrays. But in this case, subtraction is defined for the subarrays, so it can handle the nesting.

您无法统计处理对象dtype数组的数组操作。但在这种情况下,为子阵列定义减法,因此它可以处理嵌套。

Another way to do the nesting is use np.subtract. This is a ufunc version of - and will apply np.asarray to its inputs as needed:

另一种进行嵌套的方法是使用np.subtract。这是 - 的ufunc版本 - 并将根据需要将np.asarray应用于其输入:

In [103]: [np.subtract(i1,j1) for i1,j1 in zip(a,b)]
Out[103]: [array([-4, -4, -4, -4]), array([-7,  2,  2,  2]), array([-1, -1, -1, -1, -1])]

Notice that these array calculations return arrays or a list of arrays. Turning the inner arrays back to lists requires iteration.

请注意,这些数组计算返回数组或数组列表。将内部数组转回列表需要迭代。

If you are starting with lists, converting to arrays often does not save time. Array calculations can be faster, but that doesn't compensate for the overhead in creating the arrays in the first place.

如果从列表开始,转换为数组通常不会节省时间。数组计算可以更快,但这并不能弥补首先创建数组的开销。

If I pad the inputs to equal length, then the simple array subtraction works, creating a 2d array.

如果我将输入填充到相等长度,则简单数组减法有效,创建一个二维数组。

In [116]: ao= [[1,2,3,4,0], [2,3,4,5,0],[3,4,5,6,7]]; bo= [[5,6,7,8,0], [9,1,2,3,0], [4,5,6,7,8]]

In [117]: np.array(ao)-np.array(bo)
Out[117]: 
array([[-4, -4, -4, -4,  0],
       [-7,  2,  2,  2,  0],
       [-1, -1, -1, -1, -1]])

#1


1  

You can try:

你可以试试:

>>> a= [[1,2,3,4], [2,3,4,5],[3,4,5,6,7]]
>>> b= [[5,6,7,8], [9,1,2,3], [4,5,6,7,8]]
>>> 
>>> c =[]
>>> for i in range(len(a)):
    c.append([A - B for A, B in zip(a[i], b[i])])


>>> print c
[[-4, -4, -4, -4], [-7, 2, 2, 2], [-1, -1, -1, -1, -1]]

Or 2nd method is using map:

或者第二种方法是使用map:

from operator import sub
a= [[1,2,3,4], [2,3,4,5],[3,4,5,6,7]]
b= [[5,6,7,8], [9,1,2,3], [4,5,6,7,8]]
c =[]
for i in range(len(a)):
    c.append(map(sub, a[i], b[i]))  
print c
[[-4, -4, -4, -4], [-7, 2, 2, 2], [-1, -1, -1, -1, -1]]

#2


5  

Here is a Numpythonic way:

这是一种Numpythonic方式:

>>> y = map(len, a)  
>>> a = np.hstack(np.array(a))
>>> b = np.hstack(np.array(b))
>>> np.split(a-b, np.cumsum(y))
[array([-4, -4, -4, -4]), array([-7,  2,  2,  2]), array([-1, -1, -1, -1, -1]), array([], dtype=float64)]
>>> 

Since you cannot subtract the arrays with different shapes, you can flatten your arrays using np.hstack() then subtract your flattened arrays then reshape based on the previous shape.

由于无法减去具有不同形状的数组,因此可以使用np.hstack()展平数组,然后减去展平的数组,然后根据以前的形状重新整形。

#3


1  

The dimensions of your two arrays don't match, i.e. the first two sublists of a have 4 elements, but the third has 5 and ditto with b. If you convert the lists to numpy arrays, numpy silently gives you something like this:

两个数组的尺寸不匹配,即a的前两个子列表有4个元素,但第三个有5个,ditto有b。如果你将列表转换为numpy数组,numpy会默默地给你这样的东西:

In [346]: aa = np.array(a)
In [347]: bb = np.array(b)
In [348]: aa
Out[348]: array([[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6, 7]], dtype=object)
In [349]: bb
Out[349]: array([[5, 6, 7, 8], [9, 1, 2, 3], [4, 5, 6, 7, 8]], dtype=object)

You need to make sure that all your sublists have the same number of elements, then your code will work:

您需要确保所有子列表具有相同数量的元素,然后您的代码将起作用:

In [350]: a = [[1,2,3,4], [2,3,4,5],[3,4,5,6]]; b = [[5,6,7,8], [9,1,2,3], [4,5,6,7]] # I removed the last element of third sublist in a and b
In [351]: np.array(a) - np.array(b)
Out[351]: 
array([[-4, -4, -4, -4],
       [-7,  2,  2,  2],
       [-1, -1, -1, -1]])

#4


0  

Without NumPy:

没有NumPy:

result = []
for (m, n) in (zip(a, b)):
    result.append([i - j for i, j in zip(m, n)])

See also this question and this one.

另见这个问题和这个问题。

#5


0  

What about a custom function such as:

自定义功能怎么样,例如:

import numpy as np

a = [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6, 7]]
b = [[5, 6, 7, 8], [9, 1, 2, 3], [4, 5, 6, 7, 8]]


def np_substract(l1, l2):
    return np.array([np.array(l1[i]) - np.array(l2[i]) for i in range(len(l1))])

print np_substract(a, b)

#6


0  

You are getting the error, because your code is trying to subtract sublist from sublist, if you want to make it work, you can do the same in following manner:

您收到错误,因为您的代码试图从子列表中减去子列表,如果您想使其工作,您可以通过以下方式执行相同的操作:

import numpy as np
a= [[1,2,3,4], [2,3,4,5],[3,4,5,6,7]]
b= [[5,6,7,8], [9,1,2,3], [4,5,6,7,8]]

#You can apply different condition here, like (if (len(a) == len(b)), then only run the following code    
for each in range(len(a)):
    list = np.array(a[each])-np.array(b[each])
    #for converting the output array in to list
    subList[each] = list.tolist()

print subList

#7


0  

A nested list comprehension will do the job:

嵌套列表理解将完成这项工作:

In [102]: [[i2-j2 for i2,j2 in zip(i1,j1)] for i1,j1 in zip(a,b)] 
Out[102]: [[-4, -4, -4, -4], [-7, 2, 2, 2], [-1, -1, -1, -1, -1]]

The problem with np.array(a)-np.array(b) is that the sublists differ in length, so the resulting arrays are object type - arrays of lists

np.array(a)-np.array(b)的问题在于子列表的长度不同,因此生成的数组是对象类型 - 列表数组

In [104]: np.array(a)
Out[104]: array([[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6, 7]], dtype=object)

Subtraction is iterating over the outer array just fine, but hitting a problem when subtracting one sublist from another - hence the error message.

减法迭代在外部数组上很好,但是当从另一个子列表中减去一个子列表时遇到问题 - 因此出现错误消息。

If I made the inputs arrays of arrays, the subtraction will work

如果我创建了数组的输入数组,则减法将起作用

In [106]: np.array([np.array(a1) for a1 in a])
Out[106]: array([array([1, 2, 3, 4]), array([2, 3, 4, 5]), array([3, 4, 5, 6, 7])], dtype=object)

In [107]: aa=np.array([np.array(a1) for a1 in a])   
In [108]: bb=np.array([np.array(a1) for a1 in b])

In [109]: aa-bb
Out[109]: 
array([array([-4, -4, -4, -4]), 
       array([-7,  2,  2,  2]),
       array([-1, -1, -1, -1, -1])], dtype=object)

You can't count of array operations working on object dtype arrays. But in this case, subtraction is defined for the subarrays, so it can handle the nesting.

您无法统计处理对象dtype数组的数组操作。但在这种情况下,为子阵列定义减法,因此它可以处理嵌套。

Another way to do the nesting is use np.subtract. This is a ufunc version of - and will apply np.asarray to its inputs as needed:

另一种进行嵌套的方法是使用np.subtract。这是 - 的ufunc版本 - 并将根据需要将np.asarray应用于其输入:

In [103]: [np.subtract(i1,j1) for i1,j1 in zip(a,b)]
Out[103]: [array([-4, -4, -4, -4]), array([-7,  2,  2,  2]), array([-1, -1, -1, -1, -1])]

Notice that these array calculations return arrays or a list of arrays. Turning the inner arrays back to lists requires iteration.

请注意,这些数组计算返回数组或数组列表。将内部数组转回列表需要迭代。

If you are starting with lists, converting to arrays often does not save time. Array calculations can be faster, but that doesn't compensate for the overhead in creating the arrays in the first place.

如果从列表开始,转换为数组通常不会节省时间。数组计算可以更快,但这并不能弥补首先创建数组的开销。

If I pad the inputs to equal length, then the simple array subtraction works, creating a 2d array.

如果我将输入填充到相等长度,则简单数组减法有效,创建一个二维数组。

In [116]: ao= [[1,2,3,4,0], [2,3,4,5,0],[3,4,5,6,7]]; bo= [[5,6,7,8,0], [9,1,2,3,0], [4,5,6,7,8]]

In [117]: np.array(ao)-np.array(bo)
Out[117]: 
array([[-4, -4, -4, -4,  0],
       [-7,  2,  2,  2,  0],
       [-1, -1, -1, -1, -1]])