Pandasベース入門(7)Pandas反復とソート
7003 ワード
学習要約:ここをクリック
反復
Pandasオブジェクト間の基本反復の動作は、タイプによって異なります.一連を反復すると配列式と見なされ、基本反復はこれらの値を生成します.DataFrameやPanelなどの他のデータ構造は、通常の反復オブジェクトのキーに従います.簡単に言えば、基本反復(iがオブジェクト内にある場合)は、次のように生成されます. Series-値 DataFrame-カラムラベル Pannel-プロジェクトラベル 反復データFrame
反復データFrameはカラム名を指定します.
データ・フレーム(DataFrame)の行を巡回するには、次の関数を使用します. iteritems()-反復(key,value)対 iterrows()-行を(インデックス、シリーズ)対 に反復します. itertuples()-namedtuplesとして 行を反復する
1.iteritems()
各カラムをキーとし、値と値をキーとし、カラム値をSeriesオブジェクトに反復します.
2.iterrows()
iterrows()は反復器を返し、各インデックス値と各行のデータを含むシーケンスを生成します.
注意-iterrows()はローを巡回するため、ロー間でデータ型は保持されません.0,1,2は行インデックス,col 1,col 2,col 3は列インデックスである.
3.itertuples()
itertuples()メソッドは、DataFrameの各行に名前付きメタグループを生成する反復器を返します.メタグループの最初の要素は、行の対応するインデックス値であり、残りの値は行値です.
観察結果に注意し、修正の変化は反映されていない.
ツールバーの
Pandasには、次の2つのソート方法があります.ラベル 実績値
unsorted_dfデータ値では、ラベルと値はソートされません.
ラベルでソート
sort_の使用Index()メソッドでは、axisパラメータとソート順を渡すことで、DataFrameをソートできます.デフォルトでは、行ラベルは昇順にソートされます.
ソート順
ブール値を昇順パラメータに渡すことで、ソート順を制御できます.
列ごとに並べる
axisパラメータ値が0または1であることを渡すことで、カラムラベルをソートできます.デフォルトではaxis=0で、行単位で並べられます.
値でソート
インデックスソートのようにsort_values()は、値でソートする方法です.これは、値をソートするDataFrameのカラム名を使用するbyパラメータを受け入れます.
注意:上記の出力結果を観察すると、col 1値がソートされ、対応するcol 2値と行インデックスがcol 1とともに変化します.したがって、ソートされていないように見えます.
ソートアルゴリズム
sort_values()は、mergeesort、heapsort、quicksortからアルゴリズムを選択する構成を提供します.Mergesortは唯一安定なアルゴリズムである.
反復
Pandasオブジェクト間の基本反復の動作は、タイプによって異なります.一連を反復すると配列式と見なされ、基本反復はこれらの値を生成します.DataFrameやPanelなどの他のデータ構造は、通常の反復オブジェクトのキーに従います.簡単に言えば、基本反復(iがオブジェクト内にある場合)は、次のように生成されます.
反復データFrameはカラム名を指定します.
>>>import pandas as pd
>>>import numpy as np
>>>N=20
>>>df = pd.DataFrame({
'A': pd.date_range(start='2016-01-01',periods=N,freq='D'),
'x': np.linspace(0,stop=N-1,num=N),
'y': np.random.rand(N),
'C': np.random.choice(['Low','Medium','High'],N).tolist(),
'D': np.random.normal(100, 10, size=(N)).tolist()
})
>>>for col in df:
print (col)
A
C
D
x
y
データ・フレーム(DataFrame)の行を巡回するには、次の関数を使用します.
1.iteritems()
各カラムをキーとし、値と値をキーとし、カラム値をSeriesオブジェクトに反復します.
>>>import pandas as pd
>>>import numpy as np
>>>df = pd.DataFrame(np.random.randn(4,3),columns=['col1','col2','col3'])
>>>for key,value in df.iteritems():
print (key,value)
col1 0 0.802390
1 0.324060
2 0.256811
3 0.839186
Name: col1, dtype: float64
col2 0 1.624313
1 -1.033582
2 1.796663
3 1.856277
Name: col2, dtype: float64
col3 0 -0.022142
1 -0.230820
2 1.160691
3 -0.830279
Name: col3, dtype: float64
2.iterrows()
iterrows()は反復器を返し、各インデックス値と各行のデータを含むシーケンスを生成します.
>>>import pandas as pd
>>>import numpy as np
>>>df = pd.DataFrame(np.random.randn(4,3),columns = ['col1','col2','col3'])
>>>for row_index,row in df.iterrows():
print (row_index,row)
0 col1 1.529759
col2 0.762811
col3 -0.634691
Name: 0, dtype: float64
1 col1 -0.944087
col2 1.420919
col3 -0.507895
Name: 1, dtype: float64
2 col1 -0.077287
col2 -0.858556
col3 -0.663385
Name: 2, dtype: float64
3 col1 -1.638578
col2 0.059866
col3 0.493482
Name: 3, dtype: float64
注意-iterrows()はローを巡回するため、ロー間でデータ型は保持されません.0,1,2は行インデックス,col 1,col 2,col 3は列インデックスである.
3.itertuples()
itertuples()メソッドは、DataFrameの各行に名前付きメタグループを生成する反復器を返します.メタグループの最初の要素は、行の対応するインデックス値であり、残りの値は行値です.
>>>import pandas as pd
>>>import numpy as np
>>>df = pd.DataFrame(np.random.randn(4,3),columns = ['col1','col2','col3'])
>>>for row in df.itertuples():
print (row)
Pandas(Index=0, col1=1.5297586201375899, col2=0.76281127433814944, col3=-
0.6346908238310438)
Pandas(Index=1, col1=-0.94408735763808649, col2=1.4209186418359423, col3=-
0.50789517967096232)
Pandas(Index=2, col1=-0.07728664756791935, col2=-0.85855574139699076, col3=-
0.6633852507207626)
Pandas(Index=3, col1=0.65734942534106289, col2=-0.95057710432604969,
col3=0.80344487462316527)
>>>for index, row in df.iterrows():
row['a'] = 10
>>>df
col1 col2 col3
0 0.530537 -1.047444 0.667733
1 -1.039194 0.222510 0.654795
2 -0.148188 0.202904 -1.353699
3 0.225052 0.363731 0.305209
観察結果に注意し、修正の変化は反映されていない.
ツールバーの
Pandasには、次の2つのソート方法があります.
>>>import pandas as pd
>>>import numpy as np
>>>unsorted_df=pd.DataFrame(np.random.randn(10,2),index=[1,4,6,2,3,5,9,8,0,7],colu
mns=['col2','col1'])
>>>unsorted_df
col2 col1
1 1.069838 0.096230
4 -0.542406 -0.219829
6 -0.071661 0.392091
2 1.399976 -0.472169
3 0.428372 -0.624630
5 0.471875 0.966560
9 -0.131851 -1.254495
8 1.180651 0.199548
0 0.906202 0.418524
7 0.124800 2.011962
unsorted_dfデータ値では、ラベルと値はソートされません.
ラベルでソート
sort_の使用Index()メソッドでは、axisパラメータとソート順を渡すことで、DataFrameをソートできます.デフォルトでは、行ラベルは昇順にソートされます.
>>>import pandas as pd
>>>import numpy as np
>>>unsorted_df = pd.DataFrame(np.random.randn(10,2),index=[1,4,6,2,3,5,9,8,0,7],columns = ['col2','col1'])
>>>sorted_df=unsorted_df.sort_index()
>>>sorted_df
col2 col1
0 0.431384 -0.401538
1 0.111887 -0.222582
2 -0.166893 -0.237506
3 0.476472 0.508397
4 0.670838 0.406476
5 2.065969 -0.324510
6 -0.441630 1.060425
7 0.735145 0.972447
8 -0.051904 -1.112292
9 0.134108 0.759698
ソート順
ブール値を昇順パラメータに渡すことで、ソート順を制御できます.
>>>import pandas as pd
>>>import numpy as np
>>>unsorted_df = pd.DataFrame(np.random.randn(10,2),index=[1,4,6,2,3,5,9,8,0,7],columns = ['col2','col1'])
>>>sorted_df=unsorted_df.sort_index(ascending=False)
>>>sorted_df
col2 col1
9 0.750452 1.754815
8 0.945238 2.079394
7 0.345238 -0.162737
6 -0.512060 0.887094
5 1.163144 0.595402
4 -0.063584 -0.185536
3 -0.275438 -2.286831
2 -1.504792 -1.222394
1 1.031234 -1.848174
0 -0.615083 0.784086
列ごとに並べる
axisパラメータ値が0または1であることを渡すことで、カラムラベルをソートできます.デフォルトではaxis=0で、行単位で並べられます.
>>>import pandas as pd
>>>import numpy as np
>>>unsorted_df = pd.DataFrame(np.random.randn(10,2),index=[1,4,6,2,3,5,9,8,0,7],columns = ['col2','col1'])
>>>sorted_df=unsorted_df.sort_index(axis=1)
>>>sorted_df
col1 col2
1 -0.997962 0.736707
4 1.196464 0.703710
6 -0.387800 1.207803
2 1.614043 0.356389
3 -0.057181 -0.551742
5 1.034451 -0.731490
9 -0.564355 0.892203
8 -0.763526 0.684207
0 -1.213615 1.268649
7 0.316543 -1.450784
値でソート
インデックスソートのようにsort_values()は、値でソートする方法です.これは、値をソートするDataFrameのカラム名を使用するbyパラメータを受け入れます.
>>>import pandas as pd
>>>import numpy as np
>>>unsorted_df = pd.DataFrame({'col1':[2,1,1,1],'col2':[1,3,2,4]})
>>>sorted_df=unsorted_df.sort_index(by='col1')
>>>sorted_df
col1 col2
1 1 3
2 1 2
3 1 4
0 2 1
>>>sorted_df = unsorted_df.sort_values(by=['col1','col2'])
>>>sorted_df
col1 col2
2 1 2
1 1 3
3 1 4
0 2 1
注意:上記の出力結果を観察すると、col 1値がソートされ、対応するcol 2値と行インデックスがcol 1とともに変化します.したがって、ソートされていないように見えます.
ソートアルゴリズム
sort_values()は、mergeesort、heapsort、quicksortからアルゴリズムを選択する構成を提供します.Mergesortは唯一安定なアルゴリズムである.
>>>import pandas as pd
>>>import numpy as np
>>>unsorted_df = pd.DataFrame({'col1':[2,1,1,1],'col2':[1,3,2,4]})
>>>sorted_df = unsorted_df.sort_values(by='col1' ,kind='mergesort')
>>>sorted_df
col1 col2
1 1 3
2 1 2
3 1 4
0 2 1