我有一个像这样的numpy.array
[[1,2,3]
[4,5,6]
[7,8,9]]
我如何将其更改为此:-
[[[1,0], [2,0], [3,0]]
[[4,0], [5,0], [6,0]]
[[7,0], [8,0], [9,0]]]
谢谢。
答案 0 :(得分:5)
使用a
作为输入数组,您可以使用array-assignment
,这将适用于通用n-dim
输入-
out = np.zeros(a.shape+(2,),dtype=a.dtype)
out[...,0] = a
样品运行-
In [81]: a
Out[81]:
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
In [82]: out = np.zeros(a.shape+(2,),dtype=a.dtype)
...: out[...,0] = a
In [83]: out
Out[83]:
array([[[1, 0],
[2, 0],
[3, 0]],
[[4, 0],
[5, 0],
[6, 0]],
[[7, 0],
[8, 0],
[9, 0]]])
如果您使用broadcasting
,这是一个紧凑的-
a[...,None]*[1,0]
答案 1 :(得分:2)
我认为numpy.dstack可能提供解决方案。让我们将A称为第一个数组。做
B = np.zeros((3,3))
R = np.dstack((A,B))
R应该是您想要的数组。
答案 2 :(得分:2)
如果您的输入是无符号整数,并且dtype“足够大”,则可以使用以下代码填充零而不创建副本:
ww
Option Explicit
Function WorkingDaysBetween( ByVal d1, ByVal d2 )
Dim d
' Adjust date order to simplify calcs and always return 0 or positive number
If d1 > d2 Then
d = d1 : d1 = d2 : d2 = d
End If
' Move start date forward if it is a weekend
d = WeekDay( d1, vbMonday )
If d > 5 Then d1 = DateAdd( "d", 3-(d\6 + d\7), d1)
' Move end date backward if it is a weekend
d = WeekDay( d2, vbMonday )
If d > 5 Then d2 = DateAdd( "d", -1*(d\6 + d\7), d2)
' Calculate
' DateDiff("d") = Number of days between dates
' +1 to include start day
' -2 * DateDiff("ww") to exclude weekends between dates
WorkingDaysBetween = 1 + DateDiff("d", d1, d2, vbMonday) - 2*DateDiff("ww", d1, d2, vbMonday)
' If the result is negative, there are no working days between both dates
If WorkingDaysBetween < 0 Then WorkingDaysBetween = 0
End Function
等于您的示例,输出看起来像
b = str(a.dtype).split('int')
b = a[...,None].view(b[0]+'int'+str(int(b[1])//2))
答案 3 :(得分:1)
免责声明:这是快速的(适用于大型操作数),但还很不完善。而且它仅适用于32或64位dtype。请勿在严肃的代码中使用。
def squeeze_in_zero(a):
sh = a.shape
n = a.dtype.itemsize
return a.view(f'f{n}').astype(f'c{2*n}').view(a.dtype).reshape(*a.shape, 2)
在我的机器上以10000个元素快速旋转,它与@Divakar的数组分配大致相等。低于此速度较慢,高于此速度较快。
样品运行:
>>> a = np.arange(-4, 5).reshape(3, 3)
>>> squeeze_in_zero(a)
array([[[-4, 0],
[-3, 0],
[-2, 0]],
[[-1, 0],
[ 0, 0],
[ 1, 0]],
[[ 2, 0],
[ 3, 0],
[ 4, 0]]])