LoginSignup
2
2

More than 5 years have passed since last update.

Python3 + Numpy > 5列の要素を持つ二次元リストから3列だけ取出す > 思いつき実装 | より良い実装 | 内包表記

Last updated at Posted at 2018-01-26
動作環境
GeForce GTX 1070 (8GB)
ASRock Z170M Pro4S [Intel Z170chipset]
Ubuntu 16.04 LTS desktop amd64
TensorFlow v1.2.1
cuDNN v5.1 for Linux
CUDA v8.0
Python 3.5.2
IPython 6.0.0 -- An enhanced Interactive Python.
gcc (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609
GNU bash, version 4.3.48(1)-release (x86_64-pc-linux-gnu)
scipy v0.19.1
geopandas v0.3.0
MATLAB R2017b (Home Edition)
ADDA v.1.3b6

処理概要

alist = [
    [3, 1, 4, 1, 5],
    [3, 1, 4, 1, 5],
    [3, 1, 4, 1, 5],    
]
alist = np.array(alist)

上記から[3, 1, 4]の3列だけを取出す。

思いつき code

思いついたのはtranspose()を使う方法。

test_extract_array_180127.py
import numpy as np

# on Python 3.5.2

alist = [
    [3, 1, 4, 1, 5],
    [3, 1, 4, 1, 5],
    [3, 1, 4, 1, 5],    
]
alist = np.array(alist)

print(alist)

wrk = alist.transpose()[:3].transpose()
print(wrk)

run
$ python3 test_extract_array_180127.py 
[[3 1 4 1 5]
 [3 1 4 1 5]
 [3 1 4 1 5]]
[[3 1 4]
 [3 1 4]
 [3 1 4]]

リンク

https://docs.scipy.org/doc/numpy/reference/routines.array-manipulation.html
の関数を使えばもっとスマートにできるかもしれない。

より良いcode

@shiracamus さんのコメントにてもっとシンプルな書き方を教えていただきました。
情報感謝です。

この書き方は過去に(TensorFlowにて)使ったことがあるのですが、忘れていました。精進します。

test_extract_array_180127.py
import numpy as np

# on Python 3.5.2

alist = [
    [3, 1, 4, 1, 5],
    [3, 1, 4, 1, 5],
    [3, 1, 4, 1, 5],    
]
alist = np.array(alist)

print(alist)

#wrk = alist.transpose()[:3].transpose()
wrk = alist[:, :3]
print(wrk)

2
2
2

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
2
2