JavaScriptを有効にしてください

PandasのSeriesとDataFrameの作成

 ·   4 min read

はじめに

PandasはPythonのデータ解析支援用ライブラリである。Pandasの基本データ構造であるSeriesとDataFrameの作成方法について述べる。

環境

ソフトウェア バージョン
python 3.6.2
pandas 0.20.3

Pandas概要

Pandasではラベルを付与した配列を扱える。また、NumPyと異なり、1つのPandasオブジェクト内に異なるデータ型を保持できる。
扱える次元数とデータ構造の名称を下表に示す。

次元数 データ構造
1 Series
2 DataFrame
3 Panel

ただし、Pandas Ver. 0.20では、Panelの使用は非推奨である(DataFrameのMuiltiIndex で代替できるため)。

1次元データ構造Seriesの作成

1次元のデータ構造Seriesは、リスト、NumPy配列、辞書型いずれかから作成できる。ラベルはindexで指定する。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
>>> import numpy  as np
>>> import pandas as pd
>>> list_data = [1, 2, 3]  # リスト型データ
>>> Idx  = ["a", "b", "c"] # ラベル
>>> pd.Series(list_data, index=Idx) # リストからSeriesを作成
a    1
b    2
c    3
dtype: int64
>>>
>>> pd.Series(list_data) # indexを未指定の場合、ラベルは0始まりの整数
0    1
1    2
2    3
dtype: int64
>>>
>>> pd.Series(np.array(list_data), index=Idx) # NumPy配列からSeriesを作成
a    1
b    2
c    3
dtype: int64
>>>
>>> dict_data = {"c":3, "a":2, "b":1}
>>> pd.Series(dict_data)    # 辞書型から作成
a    2
b    1
c    3
dtype: int64
>>> # 辞書型では要素が順序づけされていなため、インデックスの順でソートされる

また、Seriesはnameと呼ばれる属性を持つことができる。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
>>> A = pd.Series([1, 2, 3], 
                  index=["a", "b", "c"], 
                  name="Number")           # name属性を定義
>>> A
a    1
b    2
c    3
Name: Number, dtype: int64
>>> A.name           # name属性を取得
'Number'

2次元データ構造DataFrameの作成

2次元のデータ構造DataFrameは、リスト、NumPy配列、辞書型、Pandas.Seriesから作成できる。行のラベルはindex, 列のラベルはcolumnsで指定する。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
>>> import numpy  as np
>>> import pandas as pd
>>> list_data = [[1, 2, 3], [4, 5, 6]] # 2次元のリスト型データ
>>> Idx = ["a", "b"]              # 行のラベル
>>> Col = ["one", "tow", "three"] # 列のラベル
>>> pd.DataFrame(list_data, 
                 index=Idx, 
                 columns=Col)     # リストからDataFrameを作成
   one  tow  three
a    1    2      3
b    4    5      6
>>> pd.DataFrame(list_data) 
   0  1  2
0  1  2  3
1  4  5  6
>>> # index, columnsを未指定の場合、ラベルは0始まりの整数
>>>
>>> pd.DataFrame(np.array(list_data), 
                 index=Idx, 
                 columns=Col)          # NumPy配列からDataFrameを作成
   one  tow  three
a    1    2      3
b    4    5      6
>>> dict_data = {"one":[1, 2, 3],
...              "two":[4, 5, 6]}
>>>
>>> pd.DataFrame(dict_data)            # 辞書型から作成
   one  two
0    1    4
1    2    5
2    3    6
>>>
>>> s1 = pd.Series([1, 2, 3], index=Col)
>>> s2 = pd.Series([4, 5, 6], index=Col)
>>> pd.DataFrame([s1, s2], index=Idx)   # Pandas.Seriesから作成(その1)
   one  tow  three
a    1    2      3
b    4    5      6
>>> # SeriesのindexがDataFrameのcolumnsになっていることに注意
>>>
>>> s3 = pd.Series([1, 2, 3], index=Col, name="c")
>>> s4 = pd.Series([4, 5, 6], index=Col, name="d")
>>> pd.DataFrame([s3, s4])              # Pandas.Seriesから作成(その2)
   one  tow  three
c    1    2      3
d    4    5      6
>>> # Seriesにnameが存在していれば、DataFrameのindexになる

また、DataFrame自身はname属性を持たない代わりに、indexがname属性を持つ。

1
2
3
4
5
6
7
8
9
>>> A = pd.DataFrame([[1, 2, 3], [4, 5, 6]], 
                     index=["a", "b"],
                     columns=["one", "tow", "three"])
>>> A.index.name="Row"
>>> A
     one  tow  three
Row                 
a      1    2      3
b      4    5      6

補足

欠落値を持つデータ

データの欠落箇所は、numpy.nanで補う。

1
2
3
4
5
>>> pd.Series([1, np.nan, 3], index=["a", "b", "c"])
a    1.0
b    NaN
c    3.0
dtype: float64

要素を持たないデータ

引数をとらないことにより、要素を持たないSeries, DataFrameオブジェクトを作成できる。

1
2
3
4
5
6
>>> pd.Series()
Series([], dtype: float64)
>>>pd.DataFrame()
Empty DataFrame
Columns: []
Index: []

データ型

Series, Dataframeのdtypeパラメータにより、データ型を設定できる。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
>>> pd.Series([1, 2, 3], dtype=float)
0    1.0
1    2.0
2    3.0
dtype: float64
>>> pd.Series([1, 2, 3], dtype=int)
0    1
1    2
2    3
dtype: int32

参考

Pandasの公式ドキュメントを参考とした。

Intro to data structures — pandas 1.1.5 documentation
pandas.Series — pandas 1.1.5 documentation
pandas.DataFrame — pandas 1.1.5 documentation

シェアする

Helve
WRITTEN BY
Helve
関西在住、電機メーカ勤務のエンジニア。X(旧Twitter)で新着記事を配信中です

サイト内検索