學習彙總:點這裏
迭代
Pandas對象之間的基本迭代的行爲取決於類型。當迭代一個系列時,它被視爲數組式,基本迭代產生這些值。其他數據結構,如:DataFrame和Panel,遵循類似慣例迭代對象的鍵。簡而言之,基本迭代(對於i在對象中)產生
:
- Series - 值
- DataFrame - 列標籤
- Pannel - 項目標籤
迭代DataFrame
迭代DataFrame提供列名。
>>>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)中的行,可以使用以下函數 :
- iteritems() - 迭代(key,value)對
- iterrows() - 將行迭代爲(索引,系列)對
- itertuples() - 以namedtuples的形式迭代行
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是行索引,col1,col2,col3是列索引。
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有兩種排序方式,它們分別是 :
- 按標籤
- 按實際值
>>>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()是按值排序的方法。它接受一個by參數,它將使用要與其排序值的DataFrame的列名稱。
>>>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
注意: 觀察上面的輸出結果,col1值被排序,相應的col2值和行索引將隨col1一起改變。因此,它們看起來沒有排序。
排序算法
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