この配列を基に、1 または 0 で満たされた配列を作成したい
testArray = np.array([7,5,3])
最終結果は次のようになります
[[1,1,1,1,1,1,1],
[1,1,1,1,1],
[1,1,1]]
この配列を基に、1 または 0 で満たされた配列を作成したい
testArray = np.array([7,5,3])
最終結果は次のようになります
[[1,1,1,1,1,1,1],
[1,1,1,1,1],
[1,1,1]]
これにより、不規則な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.]]
ゼロの場合は、 を使用してnp.zeros
ください。
numpy 配列のすべての行 (および列など) は、同じ長さでなければなりません。@ChrisWilson4 が行ったことを達成し、空の部分を0
orで埋めることができnp.nan
ます。行数が の長さに等しくlengths
、列数が最大の行に等しい空の配列を作成します。
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
あなたの値でそれを埋めてくださいfill
:
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.]])
または、fill = 0
およびの場合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]])
または、次のように (numpy を使用せずに) 純粋な python の方法でリストのリストを作成できます。
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]]
@JoshAdel がコメントで述べたように、int 配列をギザギザにすることはできません。つまり、行の長さを変えることはできません。これはあなたが探していたものですか?
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;
}
}
印刷されます:
1111111
1111100
1110000