I would like to generate a matrix Z_comb which consists of element z with size(len(m),len(m)). The value of z is from 0 up to (m-1).
For example:
m = [m[0],[m[1],[m[2]] = [4,2,1].
For m[0] = 2, then z[0] = [0,1] and len(m[0]) = 2
For m[1] = 4, then z[1] = [0,1,2,3] and len(m[1]) = 4
For m[2] = 1, then z[2] = [0] and len(m[2]) = 1
What is expected are: For m[0] = 2, then z[0] = [0,1, None, None] and len(m[0]) = 4
For m[1] = 4, then z[1] = [0,1,2,3] and len(m[1]) = 4
For m[2] = 1, then z[2] = [0, None, None, None] and len(m[2]) = 4
Here the code that I made:
import numpy as np
m = np.array([2,4,1])
Z_comb = np.array([np.arange(0,m[0]),np.arange(0,m[1]),np.arange(0,m[2])],dtype=object)
The printed result is
Z_comb = array([array([0, 1]), array([0, 1, 2, 3]), array([0])], dtype=object)
Expected result:
Z_comb = [[0, 1,None,None], [0, 1, 2,3], [0, None, None, None]]
Can anyone tell me what to modify for the code, please? Thank you in advance.
CodePudding user response:
You can use a list comprehension to generate the matrix Z_comb
, where for each element in m
, you create a list of integers from 0
to m[i]-1
, and then append None
to the end of the list until the length of the list is 4
. Here's an example of how you can do this:
m = [2, 4, 1]
Z_comb = [[i if i < m[j] else None for i in range(4)] for j in range(len(m))]
This will generate the expected result:
[[0, 1, None, None], [0, 1, 2, 3], [0, None, None, None]]
You can then turn Z_comb
into a numpy array if you wish.
This solution does generate what you said the expected result is, although it doesn't have size (len(m), len(m))
, which you also mention it should at the start.
CodePudding user response:
numpy solution
You can use broadcasting:
# input
m = np.array([2,4,1])
N = m.max()
# 4
a = np.arange(N)
# array([0, 1, 2, 3])
Z_comb = np.where(m[:,None] >= a, a, np.nan)
NB. the output contains nan
in place of None
as None
doesn't really make sense in a numpy array (this would force the object
dtype and prevent vectorization).
Output Z_comb
:
array([[ 0., 1., 2., nan],
[ 0., 1., 2., 3.],
[ 0., 1., nan, nan]])
pure python solution
If you want a pure python solution:
N = max(m)
Z_comb = [list(range(x)) [None]*(N-x) for x in m]
Output:
[[0, 1, None, None],
[0, 1, 2, 3],
[0, None, None, None]]
CodePudding user response:
df = pd.DataFrame(array).reshape(row,col) df.append(newrow)