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.

PythonでNumPy配列「ndarray」をliltに変換する【tolist()】

Posted at

Pythonでcsvから値を抽出して、for文で回そうと思ったら抽出したデータがndarrayという、カンマ(,)がないバージョンの配列になっていたので苦戦。 => 解決したのでメモ

抽出先のcsv

sample.csv
sample_name,sample_colomn
aaaaaaaaaaa,bbbbbbbbbbbbb
ccccccccccc,ddddddddddddd

抽出するためのロジック

sample.py

import pandas as pd
import numpy as np

sample_data = pd.read_csv('sample.csv',index_col='sample_colomn')
sample_colomn = sample_data.index.values
print(sample_colomn)

# ['bbbbbbbbbbbbb' 'ddddddddddddd']

['bbbbbbbbbbbbb' 'ddddddddddddd']をfor文で回そうとしたらTypeError: only integer scalar arrays can be converted to a scalar indexと怒られました。

対策

**tolist()**を使用して、カンマ(,)がないバージョンの配列を、普通の配列(list)に変換する

sample.py

import pandas as pd
import numpy as np

sample_data = pd.read_csv('sample.csv',index_col='sample_colomn')
sample_colomn = sample_data.index.values
print(sample_colomn.tolist())

# ['bbbbbbbbbbbbb', 'ddddddddddddd']

以上です!

参考
https://note.nkmk.me/python-numpy-list/

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?