StatsFragments

Python, R, Rust, 統計, 機械学習とか

簡単なデータ操作を Python pandas で行う

先ほどの R の記事と同じ操作を Python pandas でやる。

Python の場合は Rのようなシンボルの概念がないので、変数が評価される環境を意識する必要が(あまり)ない。

準備

サンプルデータは iris で。

補足 (11/26追記) rpy2 を設定している方は rpy2から、そうでない方は こちら から .csv でダウンロードして読み込み (もしくは read_csv のファイルパスとして直接 URL 指定しても読める)。

import pandas as pd
# 表示する行数を設定
pd.options.display.max_rows=5

# iris の読み込みはどちらかで

# rpy2 経由で R から iris をロード
# import pandas.rpy.common as com
# iris = com.load_data('iris')

# csv から読み込み
# http://aima.cs.berkeley.edu/data/iris.csv
names = ['Sepal.Length', 'Sepal.Width', 'Petal.Length', 'Petal.Width', 'Species']
iris = pd.read_csv('iris.csv', header=None, names=names)

iris 
#      Sepal.Length  Sepal.Width  Petal.Length  Petal.Width    Species
# 1             5.1          3.5           1.4          0.2     setosa
# 2             4.9          3.0           1.4          0.2     setosa
# ..            ...          ...           ...          ...        ...
# 149           6.2          3.4           5.4          2.3  virginica
# 150           5.9          3.0           5.1          1.8  virginica

列操作

列名操作

参照と変更。変更前後の列名は辞書で渡すので、可変長でも楽。

iris.columns
# Index([u'Sepal.Length', u'Sepal.Width', u'Petal.Length', u'Petal.Width', u'Species', u'Petal.Mult'], dtype='object')

iris.rename(columns={'Species': 'newcol'})
#      Sepal.Length  Sepal.Width  Petal.Length  Petal.Width     newcol
# 1             5.1          3.5           1.4          0.2     setosa
# 2             4.9          3.0           1.4          0.2     setosa
# ..            ...          ...           ...          ...        ...
# 149           6.2          3.4           5.4          2.3  virginica
# 150           5.9          3.0           5.1          1.8  virginica
変数名を用いて列選択
iris['Species'] 
# 1    setosa
# ...
# 150    virginica
# Name: Species, Length: 150, dtype: object
文字列リストを用いて、複数列を選択する
iris[['Petal.Length', 'Petal.Width']] 
#      Petal.Length  Petal.Width
# 1             1.4          0.2
# 2             1.4          0.2
# ..            ...          ...
# 149           5.4          2.3
# 150           5.1          1.8
# 
# [150 rows x 2 columns]
真偽値リストを用いて列選択する

これは R のほうがシンプル。

iris.loc[:,[False, False, True, True, False]]
#      Petal.Length  Petal.Width
# 1             1.4          0.2
# 2             1.4          0.2
# ..            ...          ...
# 149           5.4          2.3
# 150           5.1          1.8
# 
# [150 rows x 2 columns]
列の属性/値が特定の条件に該当する列を選択する

型が float の列のみ取り出す。

iris.loc[:,iris.dtypes == float]
#      Sepal.Length  Sepal.Width  Petal.Length  Petal.Width
# 1             5.1          3.5           1.4          0.2
# 2             4.9          3.0           1.4          0.2
# ..            ...          ...           ...          ...
# 149           6.2          3.4           5.4          2.3
# 150           5.9          3.0           5.1          1.8
# 
# [150 rows x 4 columns]

public ではないが数値型の列のみ取り出すメソッドもある。

iris._get_numeric_data()
#      Sepal.Length  Sepal.Width  Petal.Length  Petal.Width  Petal.Mult
# 1             5.1          3.5           1.4          0.2        0.28
# 2             4.9          3.0           1.4          0.2        0.28
# ..            ...          ...           ...          ...         ...
# 149           6.2          3.4           5.4          2.3       12.42
# 150           5.9          3.0           5.1          1.8        9.18
# 
# [150 rows x 5 columns]

行操作

値が特定の条件を満たす行を抽出する
iris[iris['Species'] == 'virginica']
#      Sepal.Length  Sepal.Width  Petal.Length  Petal.Width    Species
# 101           6.3          3.3           6.0          2.5  virginica
# 102           5.8          2.7           5.1          1.9  virginica
# ..            ...          ...           ...          ...        ...
# 149           6.2          3.4           5.4          2.3  virginica
# 150           5.9          3.0           5.1          1.8  virginica
# 
# [50 rows x 5 columns]
特定の行番号を抽出する
iris.loc[[2, 3, 4]]
#    Sepal.Length  Sepal.Width  Petal.Length  Petal.Width Species
# 2           4.9          3.0           1.4          0.2  setosa
# 3           4.7          3.2           1.3          0.2  setosa
# 4           4.6          3.1           1.5          0.2  setosa

ランダムサンプリングしたい場合は index をサンプリングしてスライス。

import random
iris.loc[random.sample(iris.index, 5)]
#      Sepal.Length  Sepal.Width  Petal.Length  Petal.Width     Species
# 64            6.1          2.9           4.7          1.4  versicolor
# 17            5.4          3.9           1.3          0.4      setosa
# 14            4.3          3.0           1.1          0.1      setosa
# 4             4.6          3.1           1.5          0.2      setosa
# 146           6.7          3.0           5.2          2.3   virginica

代入

iris['Petal.Mult'] = iris['Petal.Width'] * iris['Petal.Length']
iris
#      Sepal.Length  Sepal.Width  Petal.Length  Petal.Width    Species  \
# 1             5.1          3.5           1.4          0.2     setosa   
# 2             4.9          3.0           1.4          0.2     setosa   
# ..            ...          ...           ...          ...        ...   
# 149           6.2          3.4           5.4          2.3  virginica   
# 150           5.9          3.0           5.1          1.8  virginica   
# 
#      Petal.Mult  
# 1          0.28  
# 2          0.28  
# ..          ...  
# 149       12.42  
# 150        9.18  
# 
# [150 rows x 6 columns]

まとめ

pandas いいですよ。

Pythonによるデータ分析入門 ―NumPy、pandasを使ったデータ処理

Pythonによるデータ分析入門 ―NumPy、pandasを使ったデータ処理