0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

numpyを使ってargsortを用いず2次元配列内の数を並べ替える。

Last updated at Posted at 2019-05-13

指定した列や行を基準に2次元配列内の行や列を並べ替えたい。

Pythonを使って指定した列や行を基準に2次元配列内の行や列を並べ替えるのは、argsortを使えば簡単です。しかしここではargsortを使わない方法も併せて紹介します。


まずは argsortを使って並べ替えてみる。

argsortを使えば、簡単にできます。

import numpy as np

A = np.array([[-1, 3, -10], [1, 2, 0], [30, -10, 2], [6, 1, 4]])

# print(A)

# 3列目の要素が昇べきの順になるように行を入れ替える。
col_num = 2
A_col = A[np.argsort(A[:, col_num])]
print(A_col)

# 3列目の要素が降べきの順になるように行を入れ替える。
col_num = 2
A_col_desc = A[np.argsort(A[:, col_num])][::-1]
print(A_col_desc)

# 3行目の要素が昇べきの順になるように列を入れ替える。
row_num =2
A_row = A[:, np.argsort(A[row_num])]
print(A_row)

# 3行目の要素が降べきの順になるように列を入れ替える。
row_num =2
A_row_desc = A[:, np.argsort(A[row_num])[::-1]]
print(A_row_desc)

argsort を使わないで並べ替える。

ではargsortを使わないで並べ替えるコードを書いていきます。

3列目の要素が昇べきの順になるように行を入れ替える。
i = 0
while i < A.shape[0]:
    j = 1
    while j < A.shape[0]-i:
        if A[i][2]< A[i+j][2]:
            for k in range(A.shape[1]):
                A[i][k], A[i+j][k] = A[i+j][k], A[i][k]
            j = j+1
        else:
            j=j+1
    i = i+1

print(A)

列を入れ替えるときも同じようなコードです。

3行目の要素が昇べきの順になるように列を入れ替える。
i = 0
while i < A.shape[1]:
    j = 1
    while j < A.shape[1]-i:
        if A[2][i]< A[2][i+j]:
            for k in range(A.shape[0]):
                A[k][i], A[k][i+j] = A[k][i+j], A[k][i]
            j = j+1
        else:
            j=j+1
    i = i+1

print(A)
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?