1
4

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 5 years have passed since last update.

【Python】構造化配列作成(NumPyで異種型データ格納)

Posted at

0. 概要

名前、年齢、身長と言った具合に、ある人の情報を一括でまとめたいですよね。
そんなときはNumPyの構造化配列を使用しましょう。複合型の異なるデータを効率的に格納できます。せっかくなので乃木坂メンバーで構成してみました。(2020/02/24現在)

1. コード

list.py
# -*- coding: utf-8
import numpy as np

# 4人の情報を各配列に格納
name = ['mai', 'asuka', 'erika', 'yoda']
age = [27, 21, 23, 19]
height = [162, 158, 160, 152]

# 構造化配列の作成(3種類の配列のデータ型を決定)
data = np.zeros(4, dtype={'names' : ('name', 'age', 'height'), 'formats': ('U10', 'i4', 'f8')}) #U10 -> Unicode(10文字まで), i4 -> int32, f8 -> float64

# データ型の確認
print(data.dtype)
# [('name', '<U10'), ('age', '<i4'), ('height', '<f8')]

# 構造化配列にデータを格納
data['name'] = name
data['age'] = age
data['height'] = height

# 4人の全情報をプリント
print(data)
# [(u'mai', 27, 162.0) (u'asuka', 21, 158.0) (u'erika', 23, 160.0) (u'yoda', 19, 152.0)]

# 4人の名前をプリント
print(data['name'])
# [u'mai' u'asuka' u'erika' u'yoda']

# asukaの全情報をプリント
print(data[1])
# (u'asuka', 21, 158.0)

# maiのheightをプリント
print(data[0]['height'])
# 162.0

2. 参考書籍

オライリージャパン : Pythonデータサイエンスハンドブック

1
4
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
1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?