假设你有两个矩阵,A是2x2,B是2x7(2行,7列)。我想用A的副本创建一个形状为2x7的矩阵C.问题是np.hstack只能理解列数除的情况(例如2和8,因此你可以轻松地堆叠4个A来获得C) ,但他们什么时候不呢?有任何想法吗?
A = [[0,1] B = [[1,2,3,4,5,6,7], C = [[0,1,0,1,0,1,0],
[2,3]] [1,2,3,4,5,6,7]] [2,3,2,3,2,3,2]]
答案 0 :(得分:4)
以下是<%
revisar_url = "http://www.tutores.org"
Response.write "<br>Revisando:<b>" & revisar_url & "</b><br>"
If comprobar_componente("Msxml2.XMLHTTP") Then
Select Case Revisar_esta_url(revisar_url)
Case 200 : Response.Write "La url Si existe."
Case 404 : Response.Write "El sitio web existe, pero no la pagina especificada"
Case Else : Response.Write "La url indicada ouede que no exista"
End Select
Else
Response.Write "Necesitas tener instalado el componente Msxml2.XMLHTTP"
End if
Function comprobar_componente(ProgId)
Dim objeto_temp
On Error Resume Next
Set objeto_temp = Server.CreateObject(ProgId)
If Err.Number = 0 Then
comprobar_componente = True
Else
comprobar_componente = False
End If
Set objeto_temp = Nothing
End Function
Function Revisar_esta_url(strURL)
Dim objXML
Set objXML = CreateObject("Msxml2.XMLHTTP")
objXML.open "GET", strURL, false
On error resume next
objXML.send
Revisar_esta_url = objXML.Status
End Function
%>
-
modulus
或使用In [23]: ncols = 7 # No. of cols in output array
In [24]: A[:,np.mod(np.arange(ncols),A.shape[1])]
Out[24]:
array([[0, 1, 0, 1, 0, 1, 0],
[2, 3, 2, 3, 2, 3, 2]])
运算符 -
%
对于这样的重复索引,使用np.take
会更高效 -
In [27]: A[:,np.arange(ncols)%A.shape[1]]
Out[27]:
array([[0, 1, 0, 1, 0, 1, 0],
[2, 3, 2, 3, 2, 3, 2]])
答案 1 :(得分:0)
第一种解决方案非常好。另一种可能的方法是仍然使用hstack,但是如果你不想让模式完全重复,你可以使用数组切片来获得你需要的值:
a.shape&gt; (2,2)
b.shape&gt; (2,7)
repeats = np.int(np.ceil(b.shape[1]/a.shape[0]))
trim = b.shape[1] % a.shape[0]
c = np.hstack([a] * repeats)[:,:-trim]
&GT;
array([[0, 1, 0, 1, 0, 1, 0],
[2, 3, 2, 3, 2, 3, 2]])
答案 2 :(得分:0)
没有numpy的解决方案(虽然上面发布的np解决方案更好):
A = [[0,1],
[2,3]]
B = [[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7]]
i_max, j_max = len(A), len(A[0])
C = []
for i, line_b in enumerate(B):
line_c = [A[i % i_max][j % j_max] for j, _ in enumerate(line_b)]
C.append(line_c)
print(C)