mecobalamin’s diary

人間万事塞翁が馬

https://help.hatenablog.com/entry/developer-option

pandasでgroupbyを使う

pythonのpandasで表の集計をしている
groupbyが便利だったのでメモ

groupbyについて参考にした
Pandasのgroupbyを使った要素をグループ化して処理をする方法 - DeepAge

例えばirisのデータで種毎に平均値を計算してみる

pythonでもirisのデータが使えた
【python】iris(アヤメ)のデータセットをpandasとseabornを使って可視化する
ライブラリscikit-learnに含まれている

irisのカラムは5つ

[5 rows x 5 columns] Index(['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)',
       'petal width (cm)', 'target'],
      dtype='object')

targetが種の名前

   sepal length (cm)  sepal width (cm)  petal length (cm)  petal width (cm)  \
0                5.1               3.5                1.4               0.2   
1                4.9               3.0                1.4               0.2   
2                4.7               3.2                1.3               0.2   
3                4.6               3.1                1.5               0.2   
4                5.0               3.6                1.4               0.2   

   target  
0  setosa  
1  setosa  
2  setosa  
3  setosa  
4  setosa

groupbyでtargetを指定するとtargetで各行がまとめられて
mean()で平均値を計算してくれる

df.groupby(['target']).mean()

df.groupby(['target'])の出力は以下の通りで数値を確認できない

<pandas.core.groupby.generic.DataFrameGroupBy object at 0x07FE0310>

dict(list(df.groupby(['target'])))とすると表示できる


実際に使用したコードはこれ

import pandas as pd
from sklearn import datasets

pd.set_option('display.max_columns', 5)

iris = datasets.load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df['target'] = iris.target_names[iris.target]

print(df.head())
print(df.columns)

print(df.groupby(['target']).mean())


計算結果

            sepal length (cm)  sepal width (cm)  petal length (cm)  \
target                                                               
setosa                  5.006             3.428              1.462   
versicolor              5.936             2.770              4.260   
virginica               6.588             2.974              5.552   

            petal width (cm)  
target                        
setosa                 0.246  
versicolor             1.326  
virginica              2.026  
[Finished in 1.624s]

列が省略されないようにするにはset_optionで指定する
Pandas DataFrameの表示を省略したくない時. Jupyter… | by takkii | Music and Technology | Medium

Atomで出力している
結果が折り返されるのが修正できない。。。