1

I'm not really familiar in python in such transformations, but I need a help to transforming one 1D numpy array of shape eg. (17000) into 2D numpy array (17000, 2) in such way, that we will have such structure

1D array (value1, value2, value3, ..., value17000)
2D array ((1, value1), (2, value2), (3, value3), ... (17000, value17000))

so in short words add a new row that will have a number of index from specific order). Is there any efficient way to do this transform without writing a code, that will iterate over all values and copy that, but maybe that will do it in one-line transform?

2 Answers 2

2
result = np.column_stack((np.arange(1, len(some_np_array) + 1), some_np_array))

EDIT: I removed my previous answer because I didn't know about np.column_stack until now. For further explanation, you might want to refer to Converting two lists into a matrix

Sign up to request clarification or add additional context in comments.

5 Comments

Works nice, but I have another question, how can I make similar transform, when I have 2D array in shape (5000, 17000) and I need a transform to shape (5000,17000,2) in similar way to previous version?
@MiXen np.expand_dims(some_np_array, axis=-1). The axis argument decides where the 2 in your shape is. For example axis=1 would lead to a shape (5000, 2, 17000). Here, axis=-1 is more convenient than axis=3 because it would also cover cases, where your array has more than 3 dimensions. -1 represents always the last dimension.
*edit: Here, axis=-1 is more convenient than axis=2 ...
Okey, but I mean, that I want to transform my array adding a axis with index values, that you have done by first version from this topic.
@MiXen okay.. this is a little bit more advanced. I will write a separate answer for that.
2

There might be a better solution for your second question but this would be one:

import functools
import numpy as np

def append_idx(arr, some_iter):    
    return np.column_stack((np.fromiter(some_iter, dtype=np.int_, count=len(arr)), arr))

some_iter = iter(np.arange(1, functools.reduce(lambda x, y: x*y, some_np_array.shape) + 1))
result = np.apply_along_axis(lambda x: append_idx(x, some_iter), axis=-1, arr=some_np_array)

2 Comments

Works better, but still I see some issue, don't know if it is a desired behaviour, but I see that first row has proper indexes, but the second row start from value 17000 etc. but I need to have indexes starting from 0 in the next rows. Maybe I'm not super clear in first question, but this is crucial thing.
Ok, nevermind, I figured that by myself, thanks for help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.