How to convert a `Vec<u8>` to ndarray of any type

I have data which is a Vec<u8> and I have a datatype variable which can be something like f32, f64, complex.

How to convert the data to an ndarray in Rust or a python numpy array (by pyo3), whose data is data and dtype is according to the datatype.

so you just want to turn a Vec<u8> into a numpy array?

in that case, why not just turn the Vec<u8> into a PyList?
PyList is just a form of list[T] but in rust, so you can just call
numpy.call1 and add the PyList as the argument.

(btw, you didn't make this question as "help", you left it with no category, next time, try adding the category as help, so people can know it's a question before clicking on it)

1 Like

Does the data corespond to the binary representation of the types?

If so, the easiest is to translate this python code:

raw = bytes([1, 2, 3, 4, 5, 6, 7, 8])
arr = np.frombuffer(raw, 'uint32')
raw = vec![1u8, 2, 3, 4, 5, 6, 7, 8];
// I am not sure how pyo3 treats Vec<u8>
arr_1 = py.import("numpy")?.getattr("frombuffer")?.call1((raw, "uint32"))?;
// this isbasically np.asarray(raw).view(np.uint32)
arr_2 = PyArray::from_vec(py, raw)?.getattr('view')?.call1(("uint32",))?;

I cannot test the pyo3 code right now.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.