Home > Enterprise >  Transform python multi dimensional array 2x100 to 100x 2
Transform python multi dimensional array 2x100 to 100x 2

Time:03-29

I have the following array, is there a quick way of doing this using numpy or array?

[ ['one','two','three'] [1,2,3] ]

Need to convert it to the following

[ ['one',1], ['two',2], ['three',3] ]

Numpy or array

CodePudding user response:

q = [['one', 'two', 'three'], [1,2,3]]
a = [[s, n] for s, n in zip(*q)]
# a = [['one', 1], ['two', 2], ['three', 3]]

CodePudding user response:

a = np.array([['one','two','three'], [1,2,3]])

aT = a.T

print(aT)

CodePudding user response:

You can use zip.

a = [['one','two','three'],[1,2,3]]

new_a = [[i, j] for i, j in zip(a[0],a[1])]

print(new_a)
[['one', 1], ['two', 2], ['three', 3]]

Extra

According to the comments and the answers, I suddenly got curious with the performance time among the answer by @lhopital, my answer and the answer provided by @moe. So I have created a 2d list with 260 chars and 260 values.

%timeit [[s, n] for s, n in zip(*a)]
40.2 µs ± 2.21 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

%timeit [[i, j] for i, j in zip(a[0],a[1])]
27.2 µs ± 1.15 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

a = np.array(a)

%timeit a.T
146 ns ± 2.47 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

Apparently, np.transpose is the fastest method to use.

  • Related