pandas                
            データの索引付けと選択
        
        
            
    サーチ…
列ごとにラベルを選択
# Create a sample DF
df = pd.DataFrame(np.random.randn(5, 3), columns=list('ABC'))
# Show DF
df
          A         B         C
0 -0.467542  0.469146 -0.861848
1 -0.823205 -0.167087 -0.759942
2 -1.508202  1.361894 -0.166701
3  0.394143 -0.287349 -0.978102
4 -0.160431  1.054736 -0.785250
# Select column using a single label, 'A'
df['A']
0   -0.467542
1   -0.823205
2   -1.508202
3    0.394143
4   -0.160431
# Select multiple columns using an array of labels, ['A', 'C']
df[['A', 'C']]
          A         C
0 -0.467542 -0.861848
1 -0.823205 -0.759942
2 -1.508202 -0.166701
3  0.394143 -0.978102
4 -0.160431 -0.785250
追加情報: http : //pandas.pydata.org/pandas-docs/version/0.18.0/indexing.html#selection-by-label
ポジションで選択
 iloc ( 整数位置の略)メソッドでは、位置インデックスに基づいてデータフレームの行を選択できます。こうすることで、Pythonのリストスライシングと同様に、データフレームをスライスすることができます。 
df = pd.DataFrame([[11, 22], [33, 44], [55, 66]], index=list("abc"))
df
# Out:
#     0   1
# a  11  22
# b  33  44
# c  55  66
df.iloc[0]  # the 0th index (row)
# Out:
# 0    11
# 1    22
# Name: a, dtype: int64
df.iloc[1]  # the 1st index (row)
# Out:
# 0    33
# 1    44
# Name: b, dtype: int64
df.iloc[:2] # the first 2 rows
#     0   1
# a  11  22
# b  33  44
df[::-1]    # reverse order of rows
#     0   1
# c  55  66
# b  33  44
# a  11  22
行の位置は列の位置と組み合わせることができます
df.iloc[:, 1]  # the 1st column
# Out[15]:
# a    22
# b    44
# c    66
# Name: 1, dtype: int64
参照: 位置による選択
ラベルをスライスする
ラベルを使用する場合、開始と終了の両方が結果に含まれます。
import pandas as pd
import numpy as np
np.random.seed(5)
df = pd.DataFrame(np.random.randint(100, size=(5, 5)), columns = list("ABCDE"), 
                  index = ["R" + str(i) for i in range(5)])
# Out: 
#      A   B   C   D   E
# R0  99  78  61  16  73
# R1   8  62  27  30  80
# R2   7  76  15  53  80
# R3  27  44  77  75  65
# R4  47  30  84  86  18
行R0にR2 : 
df.loc['R0':'R2']
# Out: 
#      A   B   C   D   E
# R0   9  41  62   1  82
# R1  16  78   5  58   0
# R2  80   4  36  51  27
 ilocが終了インデックスを除外するため、 locがilocとどのように異なるかに注目してください
df.loc['R0':'R2'] # rows labelled R0, R1, R2
# Out: 
#      A   B   C   D   E
# R0   9  41  62   1  82
# R1  16  78   5  58   0
# R2  80   4  36  51  27
# df.iloc[0:2] # rows indexed by 0, 1
#      A   B   C   D   E
# R0  99  78  61  16  73
# R1   8  62  27  30  80
列CにE : 
df.loc[:, 'C':'E']
# Out: 
#      C   D   E
# R0  62   1  82
# R1   5  58   0
# R2  36  51  27
# R3  68  38  83
# R4   7  30  62
位置とラベルを組み合わせた選択の混在
DataFrame:
import pandas as pd
import numpy as np
np.random.seed(5)
df = pd.DataFrame(np.random.randint(100, size=(5, 5)), columns = list("ABCDE"), 
                  index = ["R" + str(i) for i in range(5)])
df
Out[12]: 
     A   B   C   D   E
R0  99  78  61  16  73
R1   8  62  27  30  80
R2   7  76  15  53  80
R3  27  44  77  75  65
R4  47  30  84  86  18
位置で行を選択し、ラベルで列を選択します。
df.ix[1:3, 'C':'E']
Out[19]: 
     C   D   E
R1   5  58   0
R2  36  51  27
インデックスが整数の場合、 .ixは位置ではなくラベルを使用します。 
df.index = np.arange(5, 10)
df
Out[22]: 
    A   B   C   D   E
5   9  41  62   1  82
6  16  78   5  58   0
7  80   4  36  51  27
8  31   2  68  38  83
9  19  18   7  30  62
#same call returns an empty DataFrame because now the index is integer
df.ix[1:3, 'C':'E']
Out[24]: 
Empty DataFrame
Columns: [C, D, E]
Index: []
ブールインデックス
ブール配列を使用してデータフレームの行と列を選択できます。
import pandas as pd
import numpy as np
np.random.seed(5)
df = pd.DataFrame(np.random.randint(100, size=(5, 5)), columns = list("ABCDE"), 
                  index = ["R" + str(i) for i in range(5)])
print (df)
#      A   B   C   D   E
# R0  99  78  61  16  73
# R1   8  62  27  30  80
# R2   7  76  15  53  80
# R3  27  44  77  75  65
# R4  47  30  84  86  18
mask = df['A'] > 10
print (mask)
# R0     True
# R1    False
# R2    False
# R3     True
# R4     True
# Name: A, dtype: bool
print (df[mask])
#      A   B   C   D   E
# R0  99  78  61  16  73
# R3  27  44  77  75  65
# R4  47  30  84  86  18
print (df.ix[mask, 'C'])
# R0    61
# R3    77
# R4    84
# Name: C, dtype: int32
print(df.ix[mask, ['C', 'D']])
#      C   D
# R0  61  16
# R3  77  75
# R4  84  86
列のフィルタリング(「面白い」を選択する、不要にする、RegExを使用するなど)
サンプルDFを生成する
In [39]: df = pd.DataFrame(np.random.randint(0, 10, size=(5, 6)), columns=['a10','a20','a25','b','c','d'])
In [40]: df
Out[40]:
   a10  a20  a25  b  c  d
0    2    3    7  5  4  7
1    3    1    5  7  2  6
2    7    4    9  0  8  7
3    5    8    8  9  6  8
4    8    1    0  4  4  9
文字 'a'を含む列を表示する
In [41]: df.filter(like='a')
Out[41]:
   a10  a20  a25
0    2    3    7
1    3    1    5
2    7    4    9
3    5    8    8
4    8    1    0
正規表現フィルタ(b|c|d) bまたはcまたはdを使用して列を表示する: 
In [42]: df.filter(regex='(b|c|d)')
Out[42]:
   b  c  d
0  5  4  7
1  7  2  6
2  0  8  7
3  9  6  8
4  4  4  9
 a始まる列を除くすべての列を表示a (言い換えれば、指定されたRegExを満たすすべての列を削除/削除する) 
In [43]: df.ix[:, ~df.columns.str.contains('^a')]
Out[43]:
   b  c  d
0  5  4  7
1  7  2  6
2  0  8  7
3  9  6  8
4  4  4  9
`.query()`メソッドを使って行をフィルタリング/選択する
import pandas as pd
ランダムDFを生成する
df = pd.DataFrame(np.random.randint(0,10,size=(10, 3)), columns=list('ABC'))
In [16]: print(df)
   A  B  C
0  4  1  4
1  0  2  0
2  7  8  8
3  2  1  9
4  7  3  8
5  4  0  7
6  1  5  5
7  6  7  8
8  6  7  3
9  6  4  5
列A > 2値と列B < 5値をA > 2行を選択します
In [18]: df.query('A > 2 and B < 5')
Out[18]:
   A  B  C
0  4  1  4
4  7  3  8
5  4  0  7
9  6  4  5
フィルタリングのための変数を持つ.query()メソッドの使用
In [23]: B_filter = [1,7]
In [24]: df.query('B == @B_filter')
Out[24]:
   A  B  C
0  4  1  4
3  2  1  9
7  6  7  8
8  6  7  3
In [25]: df.query('@B_filter in B')
Out[25]:
   A  B  C
0  4  1  4
パス依存スライス
次の要素または次の行が前に選択された要素または行に依存するように、一連の要素またはデータフレームの行をトラバースする必要が生じる場合があります。これはパスの依存関係と呼ばれます。
以下、時系列考えてみましょうs不規則な周波数で。 
#starting python community conventions
import numpy    as np
import pandas   as pd
# n is number of observations
n = 5000
day = pd.to_datetime(['2013-02-06'])
# irregular seconds spanning 28800 seconds (8 hours)
seconds = np.random.rand(n) * 28800 * pd.Timedelta(1, 's')
# start at 8 am
start = pd.offsets.Hour(8)
# irregular timeseries
tidx = day + start + seconds
tidx = tidx.sort_values()
s = pd.Series(np.random.randn(n), tidx, name='A').cumsum()
s.plot();
パスに依存する条件を仮定しましょう。シリーズの最初のメンバーから始めて、私はその要素と現在の要素の絶対差がx以上であるように、後続の各要素をつかみたいと思います。 
この問題は、Pythonジェネレータを使用して解決します。
ジェネレータ機能
def mover(s, move_size=10):
    """Given a reference, find next value with
    an absolute difference >= move_size"""
    ref = None
    for i, v in s.iteritems():
        if ref is None or (abs(ref - v) >= move_size):
            yield i, v
            ref = v
次に、私たちはそう新しいシリーズのmoves定義することができます
moves = pd.Series({i:v for i, v in mover(s, move_size=10)},
                  name='_{}_'.format(s.name))
両方をプロットする
moves.plot(legend=True)
s.plot(legend=True)
データフレームのアナログは次のようになります。
def mover_df(df, col, move_size=2):
    ref = None
    for i, row in df.iterrows():
        if ref is None or (abs(ref - row.loc[col]) >= move_size):
            yield row
            ref = row.loc[col]
df = s.to_frame()
moves_df = pd.concat(mover_df(df, 'A', 10), axis=1).T
moves_df.A.plot(label='_A_', legend=True)
df.A.plot(legend=True)
データフレームの最初/最後のn行を取得する
データフレームの最初または最後のレコードを表示するには、 headおよびtailメソッドを使用します
最初のn行を返すには、 DataFrame.head([n]) 
df.head(n)
最後のn行を返すには、 DataFrame.tail([n])使用します。 
df.tail(n)
引数nがなければ、これらの関数は5行を返します。
 head / tailスライス表記は次のようになります。 
df[:10]  # same as df.head(10)
df[-10:] # same as df.tail(10)
データフレーム全体で異なる行を選択する
レッツ
df = pd.DataFrame({'col_1':['A','B','A','B','C'], 'col_2':[3,4,3,5,6]})
df
# Output:
#   col_1  col_2
# 0     A      3
# 1     B      4
# 2     A      3
# 3     B      5
# 4     C      6
 col_1異なる値を取得するには、 Series.unique()使用します。 
df['col_1'].unique()
# Output:
# array(['A', 'B', 'C'], dtype=object)
しかし、 Series.unique()は単一の列に対してのみ機能します。
 SQLのcol_1 select col_1をシミュレートするには、 DataFrame.drop_duplicates()使用します。 
df.drop_duplicates()
#   col_1  col_2
# 0     A      3
# 1     B      4
# 3     B      5
# 4     C      6
これにより、データフレーム内のすべてのユニークな行が得られます。だから
df = pd.DataFrame({'col_1':['A','B','A','B','C'], 'col_2':[3,4,3,5,6], 'col_3':[0,0.1,0.2,0.3,0.4]})
df
# Output:
#   col_1  col_2  col_3
# 0     A      3    0.0
# 1     B      4    0.1
# 2     A      3    0.2
# 3     B      5    0.3
# 4     C      6    0.4
df.drop_duplicates()
#   col_1  col_2  col_3
# 0     A      3    0.0
# 1     B      4    0.1
# 2     A      3    0.2
# 3     B      5    0.3
# 4     C      6    0.4
一意レコードを選択するときに考慮する列を指定するには、それらを引数として渡します
df = pd.DataFrame({'col_1':['A','B','A','B','C'], 'col_2':[3,4,3,5,6], 'col_3':[0,0.1,0.2,0.3,0.4]})
df.drop_duplicates(['col_1','col_2'])
# Output:
#   col_1  col_2  col_3
# 0     A      3    0.0
# 1     B      4    0.1
# 3     B      5    0.3
# 4     C      6    0.4
# skip last column
# df.drop_duplicates(['col_1','col_2'])[['col_1','col_2']]
#   col_1  col_2
# 0     A      3
# 1     B      4
# 3     B      5
# 4     C      6
出典: パンダの複数のデータフレーム列にわたって「別個のものを選択する」方法 。
データが欠落している行を除外します(NaN、None、NaT)。
データが欠落しているデータフレーム( NaN 、 pd.NaT 、 None )がある場合は、不完全な行を除外することができます
df = pd.DataFrame([[0,1,2,3],
                  [None,5,None,pd.NaT],
                  [8,None,10,None],
                  [11,12,13,pd.NaT]],columns=list('ABCD'))
df
# Output:    
#     A   B   C     D
# 0   0   1   2     3
# 1 NaN   5 NaN   NaT
# 2   8 NaN  10  None
# 3  11  12  13   NaT
 DataFrame.dropnaは、データが欠落している少なくとも1つのフィールドを含むすべての行を削除します。 
df.dropna()
# Output:
#    A  B  C  D
# 0  0  1  2  3
指定された列でデータが欠落している行を削除するには、 subset 
df.dropna(subset=['C'])
# Output:
#     A   B   C     D
# 0   0   1   2     3
# 2   8 NaN  10  None
# 3  11  12  13   NaT
フィルタリングされたフレームでインプレース置換を行うには、 inplace = Trueオプションを使用します。 


