apache / apache/arrow

GH-50906: [Python] Reshape 1D tensors to 2D in SparseCSR/CSC matrix conversion

Open
#50,906 7 comments 0 reactions 1 assignee Claimed by @pratyushadk View on GitHub
Component: C++ Type: enhancement
Dominant language
C++
Stars
17.1k
Forks
4.3k
Avg merge
3d 13h
Merged PRs (30d)
88

Description

### Rationale for this change

Converting a 1D tensor to `SparseCSRMatrix` or `SparseCSCMatrix` currently fails with `NotImplemented: TODO for ndim <= 1`. Since CSR/CSC matrices are 2D structures, 1D input tensors can be reshaped to `[1, n]` on input and processed through the existing 2D conversion path, matching how scipy.sparse handles 1D arrays.

### What changes are included in this PR?

- In `MakeSparseCSXMatrixFromTensor`, detect 1D input tensors (`ndim == 1`) and reshape them to shape `[1, n]` with appropriate strides before running the standard 2D converter.
- Replaced the `TODO for ndim <= 1` in `SparseCSXMatrixConverter::Convert` with standard 2D validation (`ndim == 0 || ndim > 2` returns `Invalid`).
- Added unit tests in `sparse_tensor_test.cc` for 1D CSR matrix creation, all-zero edge cases, and dense round-trip conversion.

### Are these changes tested?

Yes, new unit tests covering 1D tensor conversion, all-zero vectors, and round-trips were added to `cpp/src/arrow/sparse_tensor_test.cc` and verified locally.

### Are there any user-facing changes?

Yes, passing 1D tensors to `SparseCSRMatrix::Make` and `SparseCSCMatrix::Make` now succeeds by reshaping the input to a 2D matrix `[1, n]` rather than returning `NotImplemented`.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.