Because TypeScript does not support Python’s arr[0:5, :] subscript syntax, numpy-ts uses string-based slicing via the .slice() method. Every slice dimension is a string argument.
const m = np.array([ [0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11],]);// shape [3, 4]// First 2 rows, all columnsm.slice('0:2', ':').toArray();// [[0, 1, 2, 3],// [4, 5, 6, 7]]// All rows, columns 1 and 2m.slice(':', '1:3').toArray();// [[1, 2],// [5, 6],// [9, 10]]// Single row (integer index reduces dimension)m.slice('1').toArray(); // [4, 5, 6, 7] (1-D result)// Submatrix: rows 0-1, columns 2-3m.slice('0:2', '2:4').toArray();// [[2, 3],// [6, 7]]
When you pass an integer as a string (e.g. '1'), that dimension is removed from the result, just like NumPy’s integer indexing. A range like '1:2' keeps the dimension.
For reading or writing individual elements, use get() and set() with an array of indices:
Copy
Ask AI
const m = np.array([[10, 20, 30], [40, 50, 60]]);// Read element at row 0, column 2m.get([0, 2]); // 30// Write element at row 1, column 1m.set([1, 1], 99);m.get([1, 1]); // 99// Negative indices work here toom.get([0, -1]); // 30 (last column of first row)m.get([-1, -1]); // 60 (last element)
The get() and set() methods require one index per dimension. Passing the wrong number of indices throws an error.
Understanding when an operation returns a view (shared data) versus a copy (new data) is important for both correctness and performance:Views (shared memory):
slice() — all slicing operations
T / transpose()
reshape() (when the array is C-contiguous)
squeeze() / expand_dims()
broadcast_to()
Copies (new data):
flatten() / copy()
take() / iindex() / bindex()
Arithmetic operations (add, multiply, etc.)
sort(), argsort()
Copy
Ask AI
const a = np.array([1, 2, 3, 4, 5]);// Slicing returns a viewconst view = a.slice('1:4');view.set([0], 99);a.toArray(); // [1, 99, 3, 4, 5] -- modified!// Flatten returns a copyconst flat = np.array([[1, 2], [3, 4]]).flatten();flat.set([0], 99);// Original is NOT affected
Check arr.base to determine if an array is a view. If base is not null, the array shares data with its base.