pythonメニュー
pandas(パンダズ)モージュールの確認
データを効率的に解析するためのライブラリで、
1次元データ用のSeries、2次元データ用のDataFrame、3次元データ用のPanel の3種類のデータ構造が扱えます。
これらは、特別にindex の属性で操作できます。
PandasはBSDライセンスのもとで提供され、次のようなインストールが必要です。
pip install pandas
1次元データ用のSeries(pandas.core.series.Series)の確認
基本的な使い方を例で示します。下記02行で生成し、aに管理させています。ここで
a.valuesで array([10, 20, 30, 50], dtype=int64)、
a.indexで Index(['a', 'b', 'c', 'd'], dtype='object')の表示結果が得られます。
import pandas as pd
a= pd.Series([10, 20, 30, 50,], index=['a', 'b', 'c', 'd'])#第2引数省略可
a['b'] # 20の表示 なお type(a)で分かるが、aは<class 'pandas.core.series.Series'>である。
[v in ('a', 'd') for v in a.index] # 結果表示 →[True, False, False, True]
a[[v in ('a', 'd') for v in a.index]] # 結果表示→ a 10
# → d 50
# → dtype: int64
a[20 < a] # 結果表示→c 30
# →d 50
# →dtype: int64
#以下のような生成も可能
dic = {'a': 10, 'b': 20, 'c': 30, 'd': 50, 'e': 50}
b = pd.Series(dic)
a+b #加算する事ができるが、index が不足した部分は 「NaN」
(a + b).isnull() #括弧で囲んで、関数を適用できる。「isnull」は「NaN or Null」かどうか判定
上記 03行まで見ると、ディクショナリに似ている使い方ができる。print(a)で表示すると次の左(1列目)の結果が得られる。
なお、Seriesコンストラクタ第2引数省略して、a= pd.Series([10, 20, 30, 50,])で生成したaを表示させると、2列目の結果が得られる。
また、011〜013で示すようにディクショナリを使った初期化もできて、print(b)の表示結果を3列目に示す。
a 10
b 20
c 30
d 50
dtype: int64
|
0 10
1 20
2 30
3 50
dtype: int64
|
a 10
b 20
c 30
d 50
e 50
dtype: int64
|
004から008の操作は、pandasの存在理由がわかる特有のものです。
なお005は、代わりに a[[True, False, False, True]] を行っても可能で、
ブーリアンの配列で行の抽出を行っている。
014で示すように、加算が可能で表示結果を左下に示す。(演算結果もpandas.core.series.Seriesになる。)
a 20.0
b 40.0
c 60.0
d 100.0
e NaN
dtype: float64
|
a False
b False
c False
d False
e True
dtype: bool
|
006行は、左上の加算結果にisnullメソッドを使った例で、上右が表示結果です。
2次元データ用のDataFrame(pandas.core.frame.DataFrame)の確認
DataFrame は2次元を扱うためのPandasのデータ型で、Series を「列」にもつ型です。
2つのSeriesでDataFrameを生成する例を示します。
import pandas as pd
a= pd.Series([10, 20, 30, 50,], index=['a', 'b', 'c', 'd'])
b = pd.Series({'a': 10, 'b': 20, 'c': 30, 'd': 50, 'e': 50})
c = pd.DataFrame([a, b]) # a,bの2つのSeriesでDataFrameを生成
c
c.values
c.index
上記実行の表示結果を示します。
| cの表示 | c.valuesの表示 | c.indexの表示 |
a b c d e
0 10.0 20.0 30.0 50.0 NaN
1 10.0 20.0 30.0 50.0 50.0
|
array([[10., 20., 30., 50., nan],
[10., 20., 30., 50., 50.]])
|
RangeIndex(start=0, stop=2, step=1)
|
Seriesを使わず、直接にDataFrameを生成する例を以下に示します。(columnsの属性あることに注目)
>>> d=pd.DataFrame([[1, 2,'XX'], [3, 4,'YY'], [5, 6,'Z']], columns=['a', 'b', 'c'])
>>> d
a b c
0 1 2 XX
1 3 4 YY
2 5 6 Z
>>> d['a']
0 1
1 3
2 5
Name: a, dtype: int64
>>> d.a #(上記と同じ表現です。)
0 1
1 3
2 5
>>> d.a[1] #( d['a'][1]と同じ表現です。)
3
>>> d.b[2] #( d['b'][2]と同じ表現です。)
6
>>> d[1:2] # 1行から2行を抽出
a b c
1 3 4 YY
>>> d.values
array([[1, 2, 'XX'],
[3, 4, 'YY'],
[5, 6, 'Z']], dtype=object)
>>> d.index
RangeIndex(start=0, stop=3, step=1)
>>> d.columns
Index(['a', 'b', 'c'], dtype='object')
なお、columnsが並べたデータ数と合わないとエラーです。(valueの数に不足があってもエラー)
DataFrameのmapを使うと、
特定の列を加工した列のDataFrameを取得できます。以下でその例を示します。
>>> d=pd.DataFrame([[1, 2,'XX'], [3, 4,'YY'], [5, 6,'Z']], columns=['a', 'b', 'c'])
>>> d
a b c
0 1 2 XX
1 3 4 YY
2 5 6 Z
>>> d['b'].map(lambda x : 'XXX' + str(x))
0 XXX2
1 XXX4
2 XXX6
Name: b, dtype: object
>>>
Pandas では様々なファイルを読み込み操作をサポートしています
下記内容で、t1.csvのファイルある例で示します。
ID,W,H
AAA,12,333
BBB,456,78
このファイルを読み取って操作するコード例を示します。
import pandas as pd
with open('t1.csv') as i_:
z = pd.read_csv(i_)
print(z)
print(type(z)) #<class 'pandas.core.frame.DataFrame'>の型が戻る。
以下がprint(z)実行の表示結果です。
ID W H
0 AAA 12 333
1 BBB 456 78
そのまま、zのコマンド操作の例を示します。
>>> z['ID'] # columns操作例 この結果はSeries
0 AAA
1 BBB
Name: ID, dtype: object
>>> z[['ID']] # columns操作例 この結果はDataFrame
0 AAA
1 BBB
>>> z[['ID','H']] # 結果はDataFrame
ID H
0 AAA 333
1 BBB 78
>>> z[0:1] #index操作例で0から1列と指定。結果はDataFrame
ID W H
0 AAA 12 333
>>> z[1:2] #index操作例で1から2列と指定
ID W H
1 BBB 456 78
>>> z['W'][1:2] #columnsとindex操作例 結果はSeries
1 456
Name: W, dtype: int64
>>> z[['W','ID']][1:2] # columnsとindex操作例 結果はDataFrame
W ID
1 456 BBB
>>> z.dtypes # 内部のデータ型を取得 結果はSeries
ID object
W int64
H int64
dtype: object
>>> z.loc[1] # 行は「loc」で取得できます。結果はSeries
ID BBB
W 456
H 78
Name: 1, dtype: object
>>> z.info() # これで、情報の概要が分かります。
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 2 entries, 0 to 1
Data columns (total 3 columns):
ID 2 non-null object
W 2 non-null int64
H 2 non-null int64
dtypes: int64(2), object(1)
memory usage: 128.0+ bytes
>>>
なお他に、「read_excel」メソッドでExcelを(xlrd ライブラリ等が必要)、
「read_html」メソッドでHTMLを読む事ができます。
3次元データ用のPanel(pandas.core.panel.Panel)の確認
「Panel」は「DataFrame」から構成されます。例を示します。
import pandas as pd
d0=pd.DataFrame([[ 1, 2.0], [ 3, 4.0], [ 5, 6.0]], columns=['a', 'b'])
d1=pd.DataFrame([[ 7, 8.0], [ 9, 10.0], [11, 12.0]], columns=['a', 'b'])
d2=pd.DataFrame([[13, 14.0], [15, 16.0], [17, 18.0]], columns=['a', 'b'])
p=pd.Panel({'1': d0, '2': d1, '3': d2})
pのコマンド操作を示します。
>>> p
<class 'pandas.core.panel.Panel'>
Dimensions: 3 (items) x 3 (major_axis) x 2 (minor_axis)
Items axis: 1 to 3
Major_axis axis: 0 to 2
Minor_axis axis: a to b
>>> p['2']
a b
0 7.0 8.0
1 9.0 10.0
2 11.0 12.0
>>> type(p['2'])
<class 'pandas.core.frame.DataFrame'>
>>>