pandas入門3_「indexのあれこれ」
こんにちは、ワタルです。
さっと見て、「あぁそうだったそうだった」と確認できるハンドブックのような存在を目指して。
pandas入門第3回目、「indexのあれこれ」です。
今回では、以下の関数を使えるようになることが目標です。
ser2 = ser1.reindex(['index1','index2','index3'])(indexを変える) #reindexの引数(fill_value=)(新しいindexの値を指定して埋める) #reindexの引数(method='ffill')(次の値が存在するまで、その値で埋める)
おまじない
import numpy as np from pandas import Series, DataFrame import pandas as pd from numpy.random import randn
ser2 = ser1.reindex(['index1','index2','index3'])(indexを変える)
#まずは、Seriesをつくります ser1 = Series([1,2,3,4],index=['A','B','C','D']) ser1 >>> A 1 B 2 C 3 D 4 dtype: int64
#reindexを使って、indexを変えます。 ser2 = ser1.reindex(['A','B','C','D','E','F']) ser2 >>> #要素が存在しない場所には、nullが入ります。 A 1 B 2 C 3 D 4 E NaN F NaN dtype: float64
reindexの引数(fill_value=)(新しいindexの値を指定して埋める)
#新しいindexの値を埋めることもできます。 ser2.reindex(['A','B','C','D','E','F','G'],fill_value=0) >>> #新しいindexのGに0が入ったことがわかります A 1 B 2 C 3 D 4 E NaN F NaN G 0 dtype: float64
reindexの引数(method='ffill')(次の値が存在するまで、その値で埋める)
#新しいSeriesをつくります ser3 = Series(['USA','Mexico','Canada'],index=[0,5,10]) ser3 >>> 0 USA 5 Mexico 10 Canada dtype: object
ser3.reindex(range(15),method='ffill')#ffillは、forward fillの略です。 >>> #次の値が存在するまで、その値が入力されていることがわかります 0 USA 1 USA 2 USA 3 USA 4 USA 5 Mexico 6 Mexico 7 Mexico 8 Mexico 9 Mexico 10 Canada 11 Canada 12 Canada 13 Canada 14 Canada dtype: object
DataframeのReindex
#まずは、5×5のDataFrameをつくります dframe = DataFrame(randn(25).reshape((5,5)),index=['A','B','D','E','F'],columns=['col1','col2','col3','col4','col5']) dframe >>>
col1 | col2 | col3 | col4 | col5 | |
---|---|---|---|---|---|
A | -0.833892 | 0.096806 | -0.546194 | 0.284642 | 0.938754 |
B | -0.040001 | -0.779153 | 1.248989 | -1.088699 | 0.087533 |
D | -0.767749 | 0.577453 | -1.241944 | 1.814318 | -0.374022 |
E | -1.579335 | -1.407157 | 2.671767 | -1.120105 | 1.161817 |
F | -1.458378 | 1.330623 | -1.773946 | 0.626151 | 1.362205 |
#新しいindexと新しいcolumnsのlistをつくります new_index = ['A','B','C','D','E','F'] new_columns = ['col1','col2','col3','col4','col5','col6'] #new_indexとnew_columnsを同時に追加します dframe.reindex(index = new_index,columns = new_columns) >>> #indexがC行の行と、columnsがcol6の列が追加されていることがわかります
col1 | col2 | col3 | col4 | col5 | col6 | |
---|---|---|---|---|---|---|
A | -0.833892 | 0.096806 | -0.546194 | 0.284642 | 0.938754 | NaN |
B | -0.040001 | -0.779153 | 1.248989 | -1.088699 | 0.087533 | NaN |
C | NaN | NaN | NaN | NaN | NaN | NaN |
D | -0.767749 | 0.577453 | -1.241944 | 1.814318 | -0.374022 | NaN |
E | -1.579335 | -1.407157 | 2.671767 | -1.120105 | 1.161817 | NaN |
F | -1.458378 | 1.330623 | -1.773946 | 0.626151 | 1.362205 | NaN |
今回では、SeriesやDataframeのindexやcolumnsを追加したり、変更したりする方法について学びました。 お疲れ様でした!
次回はこちら。
それじゃー、また。