LoginSignup
0
4

More than 5 years have passed since last update.

Pandas: DataFrame と Series の numpy との対応

Posted at

お恥ずかしい話ですが、しょっちゅう間違えるのでメモします。

  • Series から values で np.array を作る時: 縦方向の一次元配列が返る。
    • 例: [1,2,3,4,5]
  • DataFrame から values で np.array を作る時: 二次元配列だが、内側の配列は横方向。
    • 例: [[1], [2], [3], [4], [5]]
    • 間違い: [[1,2,3,4,5]]

特に DataFrame のインデクサがスカラの時 Series を返し、リストの時 DataFrame を返すので間違いやすい。
例えばこんな Pandas の表があるとします。

import pandas as pd
sales = pd.DataFrame([
    ['apple'],
    ['orange'],
    ['mango'],
    ['melon'],
    ['banana']],
    columns=['name'])
sales
name
0 apple
1 orange
2 mango
3 melon
4 banana

ここからカラムを選択する時、インデクサがスカラだと Series を得るので

sales['name']
0     apple
1    orange
2     mango
3     melon
4    banana
Name: name, dtype: object

これを values すると shape (5, ) の一次元配列を得る。

print('shape:', sales['name'].shape)
sales['name'].values
shape: (5,)

array(['apple', 'orange', 'mango', 'melon', 'banana'], dtype=object)

インデクサがリストだと DataFrame を得るので

sales[['name']]
name
0 apple
1 orange
2 mango
3 melon
4 banana

これを values すると shape (5,1) の二次元配列を得る。

print('shape:', sales[['name']].shape)
sales[['name']].values
shape: (5, 1)

array([['apple'],
       ['orange'],
       ['mango'],
       ['melon'],
       ['banana']], dtype=object)

[['apple', 'orange', 'mango', 'melon', 'banana']] では無いので注意!

別の言い方をすると次のような関係です。

sales['name'].values == sales[['name']].values.transpose()[0]
array([ True,  True,  True,  True,  True])
0
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
0
4