Pandas基础入门(7)Pandas迭代和排序

学习汇总:点这里

迭代

Pandas对象之间的基本迭代的行为取决于类型。当迭代一个系列时,它被视为数组式,基本迭代产生这些值。其他数据结构,如:DataFrame和Panel,遵循类似惯例迭代对象的键。简而言之,基本迭代(对于i在对象中)产生
:

  1. Series - 值
  2. DataFrame - 列标签
  3. 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)中的行,可以使用以下函数 :

  1. iteritems() - 迭代(key,value)对
  2. iterrows() - 将行迭代为(索引,系列)对
  3. 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有两种排序方式,它们分别是 :

  1. 按标签
  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()是按值排序的方法。它接受一个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

你可能感兴趣的:(Python)