Python Tutorial:PandasシリーズとPandasデータフレーム

その買うを、もっとハッピーに。|ハピタス

このサイトのPythonチュートリアルをやってみる。

スポンサーリンク

Pandas Series

# jupyter magics
%matplotlib inline
%config IPCompleter.greedy=True

# multiple output
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
import numpy as np
import pandas as pd
from pandas import Series, DataFrame

Series is a mutable 1D datatype in Pandas (any numpy datatype). Series uses explicit indices with Series datatype. Indices can be added automatically from 0 to len(data):
シリーズは、Pandas(全numpyデータ型)の可変1次元データ型で、シリーズデータ型を持った明示的なインデックスを使用する。インデックスは、0から全データ数まで自動的に付加される。

np.random.seed(0)
mySeries0 = Series(np.random.normal(size=(8,)))
print(mySeries0.values)
print(mySeries0.index)
print(mySeries0[mySeries0.last_valid_index()]) # -1 throws an error
[ 1.76405235  0.40015721  0.97873798  2.2408932   1.86755799 -0.97727788
  0.95008842 -0.15135721]
RangeIndex(start=0, stop=8, step=1)
-0.1513572082976979

Or the index can be manually set:
または、インデックスは手入力でセットできる。

np.random.seed(1)
mySeries1 = Series(np.random.normal\
 (size=(8,)), index=\
  ['a','b','c','d','e','f','g','h'])
mySeries1.name = 'random_norm'
mySeries1.index.name = 'code'
print(mySeries1)
print()
print('Values: ', mySeries1.values)
print('Index: ', mySeries1.index)
print('Element at index ["a"]: ' + str(mySeries1['a']))
code
a    1.624345
b   -0.611756
c   -0.528172
d   -1.072969
e    0.865408
f   -2.301539
g    1.744812
h   -0.761207
Name: random_norm, dtype: float64

Values:  [ 1.62434536 -0.61175641 -0.52817175 -1.07296862  0.86540763 -2.3015387
  1.74481176 -0.7612069 ]
Index:  Index(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'], dtype='object', name='code')
Element at index ["a"]: 1.6243453636632417

All numpy operations can be applied to Series without losing the data structure.
全てのnumpy演算は、データ構造を失うことなしにシリーズに適用することができる。

np.sign(mySeries1)
code
a    1.0
b   -1.0
c   -1.0
d   -1.0
e    1.0
f   -1.0
g    1.0
h   -1.0
Name: random_norm, dtype: float64

Series are basically ordered key-value pairs and can be created directly from a Python dictionary.
シリーズは、基本的に、キーと値のペアに順序付けられ、Python辞書から直接作成することができる。

myDict = {'s0':15,'s1':22,'s2':19,\
  's3':32,'s4':8,'s5':26,'s6':39,'s7':3}
mySeries2 = Series(myDict, name='subjects')
print(mySeries2)
s0    15
s1    22
s2    19
s3    32
s4     8
s5    26
s6    39
s7     3
Name: subjects, dtype: int64
スポンサーリンク

Pandas Dataframe

Dataframe is a mutable 2D data type (=table). Dataframe is characterized by labels (for each column) and indices (for each row). Dataframe can have mixed data types in different columns.
データフレームは、可変可能な二次元データ型(テーブル)で、ラベル(列用)とインデックス(行用)によって特徴付けられ、それぞれの列に異なるデータ型を有することができる。

To display the data use .head() method.
データ表示には.head() methodを使う。

codes = ['sm', 'at', 'ap', 'gs', 'rd']
age = [15, 22, 19, 32, 28]
handedness = ['l', 'l', 'l', 'r', 'r']
experiment = ['AB', 'BA', 'BA', 'AB', 'AB']
performance = [89, 78, 95, 89, 79]
df = DataFrame({'codes': codes, 'age': age, 'handedness': handedness, 'experiment':experiment, 'performance':performance}, 
              index=['s0', 's1', 's2', 's3', 's4'])
df
df.head(2)
codes age handedness experiment performance
s0 sm 15 l AB 89
s1 at 22 l BA 78
s2 ap 19 l BA 95
s3 gs 32 r AB 89
s4 rd 28 r AB 79
codes age handedness experiment performance
s0 sm 15 l AB 89
s1 at 22 l BA 78

Dataframe columns and index:
データフレーム列とインデックス

print('Columns:', df.columns)
print('Rows:', df.index)
Columns: Index(['codes', 'age', 'handedness', 'experiment', 'performance'], dtype='object')
Rows: Index(['s0', 's1', 's2', 's3', 's4'], dtype='object')
スポンサーリンク

Indexing and data selection

Dataframe data can be indexed by column or by row. However, indices can be label-based (.loc) or position-based (.iloc).
データフレームデータは、列とコラムでインデックス化できるが、ラベルベース(.loc)、もしくは、位置ベース(.iloc)にすることができる。

If you index the entire row/column, the operation returns a 1D Pandas Series.
全ての行/列をインデックスする場合、その操作は、1次元Pandasシリーズを返す。

Entire row by label:
ラベルによる全行

# row by label
df.loc['s0']
codes          sm
age            15
handedness      l
experiment     AB
performance    89
Name: s0, dtype: object

Entire row by position:
位置による全行

# row by position
df.iloc[0]
# print(df.iloc[[0]]) returns a dataframe: using [[]] returns a DataFrame
codes          sm
age            15
handedness      l
experiment     AB
performance    89
Name: s0, dtype: object

Entire column by label:
ラベルによる全列

# column by label
df.loc[:, 'age']
s0    15
s1    22
s2    19
s3    32
s4    28
Name: age, dtype: int64

Entire column by position:
位置による前列

# column by position
df.iloc[:, 1]
s0    15
s1    22
s2    19
s3    32
s4    28
Name: age, dtype: int64

Column data can also be accessed by using a dictionary-like or object-like syntax:
列データは、辞書様、または、オブジェクト様構文を使うことでアクセスできる。

Note: row data was previously accessible by using .ix(index), but it has now been deprecated in favor of .loc and .iloc
注釈:行データは、前回、.ix(index)を使うことでアクセスできたが、今は、.locと.ilocの方が好んで使われるので非推奨となっている。

print('Entire column ["age"]:')
df['age']
df.age
Entire column ["age"]:
s0    15
s1    22
s2    19
s3    32
s4    28
Name: age, dtype: int64
s0    15
s1    22
s2    19
s3    32
s4    28
Name: age, dtype: int64

Accessing single values is done by specifying both indices in .loc or .iloc:
単一値には、.locか.ilocの両インデックスを特定することでアクセスする。

print(df.loc['s0']['age'])
print(df.iloc[0][1])
15
15

Often it is useful to select data based on a condition (boolean indexing):
多くの場合、コンディションベースでデータを選択する(ブールインデックス作成)のが良い。

df[df['age']>18] # dataframe

df[(df['age']>18) & (df['performance']>80)] # dataframe

df[((df['age']>30) & (df['performance']<80)) |((df['age']<18) & (df['performance']>80))] # dataframe
codes age handedness experiment performance
s1 at 22 l BA 78
s2 ap 19 l BA 95
s3 gs 32 r AB 89
s4 rd 28 r AB 79
codes age handedness experiment performance
s2 ap 19 l BA 95
s3 gs 32 r AB 89
codes age handedness experiment performance
s0 sm 15 l AB 89
スポンサーリンク
スポンサーリンク