0

I am trying to reshape an array of shape (1, 400) to (20, 20) with numpy arrays and am struggling to find the proper syntax.

Consider the following:

import numpy as np

d_array = np.ones((1 + 10 * (20 + 1), 1 + 10 * (20 + 1)))

# tA and tB have shape (20,)
tA = np.array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
tB = np.array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])

# X is a matrix of shape (5000, 400)
X = np.loadtxt(open("X.csv", "rb"), delimiter=",", skiprows=0)

Trying to assign and reshape at the same time doesn't seem to work with the way I'm doing it (below). I not sure of the proper syntax for this type of operation. Please help me understand what I'm doing wrong here.

Throws an error of: value array of shape(20,20) could not be broadcast to indexing result of shape(20,)

# save an array of first row from sample data of shape(1, 400)
xA = np.array([X[0, :]])

# try to assign both tA of shape(20,) and tB of shape(20,)
# a reshaped version of xA (20x20 = 400)
d_array [tA, tB] = np.reshape(xA, (20, 20))

I'm simply trying to create 20 reshaped arrays containing the 20 indices of each array (20x20)=400. I'm new to numpy, but am excited to learn more. Thanks for any help anyone can provide!

JustinTime
  • 55
  • 7
  • Could you explain what do you want to do by line: `d_array [tA, tB] = np.reshape(xA, (20, 20))`? – Erfan Loghmani Oct 30 '19 at 19:48
  • Yes, that's the part that I'm stuck on. – JustinTime Oct 30 '19 at 19:54
  • Do you want to modify `d_array`? If so why don't you use `d_array[:20, :20] = np.reshape(xA, (20, 20))`. If you want to modify `tA` or `tB` then why is `d_array` there? – Erfan Loghmani Oct 30 '19 at 19:58
  • Within the d_array, I want to assign a re-shaped version of xA wherein each array of indices (tA and tB) would be assigned to a row and column within the d_array. – JustinTime Oct 30 '19 at 20:02
  • So in the original setting `tA` and `tB` are not filled with ones and contain row/column indices? – Erfan Loghmani Oct 30 '19 at 20:08
  • For instance, I've used just a simple array of ones to explain, but the final code will contain arrays of indices create dynamically, i.e. tA = [102, 110, ... , 100, 245] of shape(20,) – JustinTime Oct 30 '19 at 20:08

2 Answers2

0

You can use:

d_array[tA.reshape(-1, 1), tB] = np.reshape(xA, (20, 20))

I think this question is also related to your case.

Erfan Loghmani
  • 607
  • 4
  • 7
0

You can use np.ix_:

d_array [np.ix_(tA, tB)] = np.reshape(xA, (20, 20))

Indexing with two equal length 1D arrays returns or assigns to a 1D array of the same length, namely [d_array[tA[0],tB[0]],d_array[tA[1],tB[1]],...]. If instead you want the product you need to reshape tA and tB such that they broadcast together to form a 2D grid. This can be manually or---more conveniently---using np.ix_

Paul Panzer
  • 51,835
  • 3
  • 54
  • 99