Fill 2d array value in python with another 1d array per column
Question:
I have this code :
series =[]
list = type.groupby('level').size()
that list is equal = [20,40,40]
So, I want to have this loop:
series[0:3]=list
until here, its work but I want to have 2d matrix so I can save that list value for each loop.
matrixb=np.zeros((3,15))
for i in range (15):
matrix[0:3][i]=series[0:3]
it does not work,
could not broadcast input array from shape (3,) into shape (15,)
Answers:
You can’t perform such an assignment. You’d need to break them up as such:
for i in range (15):
matrix[0][i] = series[0]
matrix[1][i] = series[1]
matrix[2][i] = series[2]
You can actually do it like this:
list = [20, 40, 40]
series = list.copy()
matrix = np.zeros((3,15))
for i in range(15):
matrix[:,i] = series
which gives matrix
:
[[20. 20. 20. 20. 20. 20. 20. 20. 20. 20. 20. 20. 20. 20. 20.]
[40. 40. 40. 40. 40. 40. 40. 40. 40. 40. 40. 40. 40. 40. 40.]
[40. 40. 40. 40. 40. 40. 40. 40. 40. 40. 40. 40. 40. 40. 40.]]
I have this code :
series =[]
list = type.groupby('level').size()
that list is equal = [20,40,40]
So, I want to have this loop:
series[0:3]=list
until here, its work but I want to have 2d matrix so I can save that list value for each loop.
matrixb=np.zeros((3,15))
for i in range (15):
matrix[0:3][i]=series[0:3]
it does not work,
could not broadcast input array from shape (3,) into shape (15,)
You can’t perform such an assignment. You’d need to break them up as such:
for i in range (15):
matrix[0][i] = series[0]
matrix[1][i] = series[1]
matrix[2][i] = series[2]
You can actually do it like this:
list = [20, 40, 40]
series = list.copy()
matrix = np.zeros((3,15))
for i in range(15):
matrix[:,i] = series
which gives matrix
:
[[20. 20. 20. 20. 20. 20. 20. 20. 20. 20. 20. 20. 20. 20. 20.]
[40. 40. 40. 40. 40. 40. 40. 40. 40. 40. 40. 40. 40. 40. 40.]
[40. 40. 40. 40. 40. 40. 40. 40. 40. 40. 40. 40. 40. 40. 40.]]