tensor([[17, 0],
[93, 0],
[0, 0],
[21, 0],
[19, 0])
I want to remove 0 from this tensor, which is a two-dimensional array, and make it a one-dimensional array.
How can I make this tensor with the tensor below?
tensor([[17],
[93],
[0],
[21],
[19])
When using the code below, there is a problem that the existing zero disappears. How should I fix this?
x = x.flatten()
x = x[x!=0]
x = np.reshape(x, ( -1, x.shape[0] ))
array([[17, 93, 21, 19]])
CodePudding user response:
You can use slicing to index the 0
column
import torch
t = torch.tensor(
[[17, 0],
[93, 0],
[0, 0],
[21, 0],
[19, 0]]
)
print(t[:,0])
Output
tensor([17, 93, 0, 21, 19])
And if you want to keep it a 2D array then you can use numpy.reshape
import torch
import numpy as np
t = torch.tensor(
[[17, 0],
[93, 0],
[0, 0],
[21, 0],
[19, 0]]
)
print(np.reshape(t[:,0], (-1, 1)))
Output
array([[17],
[93],
[ 0],
[21],
[19]], dtype=int32)