Reputation: 17
I want to create an array filled with ones or zeros based on this array
testArray = np.array([7,5,3])
so the final result should look like
[[1,1,1,1,1,1,1],
[1,1,1,1,1],
[1,1,1]]
Upvotes: 2
Views: 155
Reputation: 17829
just write a quick list comprehension:
>>> holder = [np.ones((testArray[i])) for i in range(len(testArray))]
>>> holder
[array([[ 1., 1., 1., 1., 1., 1., 1.]]), array([[ 1., 1., 1., 1., 1.]]), array([[ 1., 1., 1.]])]
if you want it to be in the write format you can always reshape it:
>>> np.array(holder).reshape(3,1)
array([[array([ 1., 1., 1., 1., 1., 1., 1.])],
[array([ 1., 1., 1., 1., 1.])],
[array([ 1., 1., 1.])]], dtype=object)
problem solved!
Upvotes: 1
Reputation: 46530
Every row (and column, etc) in a numpy array must have the same length. You can achieve what @ChrisWilson4 did, and fill the empty parts with 0
or np.nan
. Create an empty array with number of rows equal to length of lengths
, and number of columns equal to the largest row:
fill = 1 # or `0` or `np.nan`
background = 0 # or `np.nan`
lengths = np.array([7,5,3])
a = np.ones((lengths.size, lengths.max()))*background
and fill it up with your fill
value:
for row, length in enumerate(lengths):
a[row,:length] = fill
a
#array([[ 1., 1., 1., 1., 1., 1., 1.],
# [ 1., 1., 1., 1., 1., 0., 0.],
# [ 1., 1., 1., 0., 0., 0., 0.]])
Or, for fill = 0
and background = np.nan
:
array([[ 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., nan, nan],
[ 0., 0., 0., nan, nan, nan, nan]])
Or, you can make a list of lists, in the pure python way (without using numpy) like so:
fill = 1
lengths = [7,5,3]
a = [ [fill]*length for length in lengths ]
a
#[[1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1]]
Upvotes: 1
Reputation: 23492
This will give you a ragged array of object
dtype:
>>> result = np.array([np.ones(a) for a in testArray])
>>> print result
[[ 1. 1. 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1.] [ 1. 1. 1.]]
For zeros, just use np.zeros
.
Upvotes: 1
Reputation: 195
Like @JoshAdel said in comments, the int array cannot be jagged, meaning the rows can't be different lengths. Is this what you were looking for?
public class soArray {
public static void main(String[] args) {
int[][] testArray = soArray.array(7,5,3);
for (int i = 0; i < testArray.length; i++){
for (int j = 0; j < testArray[0].length; j++){
System.out.print(testArray[i][j]);
}
System.out.println();
}
}
public static int[][] array(int a, int b, int c){
int max;
if(a > b && a > c)
max = a;
else if(b > a && b > c)
max = b;
else
max = c;
int[][] out = new int[3][max];
for (int i = 0; i < max; i++){
if(i < a)
out[0][i] = 1;
else
out[0][i] = 0;
}
for(int i = 0; i< b; i++){
if(i < b)
out[1][i] = 1;
else
out[1][i] = 0;
}
for(int i = 0; i < c; i++){
if(i < c)
out[2][i] = 1;
else
out[2][i] = 0;
}
return out;
}
}
It will print out :
1111111
1111100
1110000
Upvotes: -1