Series和DataFrame的排序
Series和DataFrame的排序
引入相关库
import numpy as np
import pandas as pd
from pandas import Series,DataFrame
Series的排序
创建一个随机的长度为10的Series
s1=Series(np.random.randn(10))
s1
0 0.614174
1 -0.595162
2 0.070313
3 0.505122
4 0.415065
5 0.563751
6 -0.860390
7 0.984829
8 0.902218
9 1.318534
dtype: float64
查看Series的value
s1.values
array([ 0.61417359, -0.59516151, 0.07031315, 0.50512192, 0.41506494,
0.56375129, -0.86039027, 0.9848288 , 0.90221807, 1.31853387])
查看Series的index
s1.index
RangeIndex(start=0, stop=10, step=1)
从小到大排序
s2=s1.sort_values()
s2
6 -0.860390
1 -0.595162
2 0.070313
4 0.415065
3 0.505122
5 0.563751
0 0.614174
8 0.902218
7 0.984829
9 1.318534
dtype: float64
进行降序排序
s2=s1.sort_values(ascending=False)
s2
9 1.318534
7 0.984829
8 0.902218
0 0.614174
5 0.563751
3 0.505122
4 0.415065
2 0.070313
1 -0.595162
6 -0.860390
dtype: float64
根据index进行排序
s2.sort_index()
DataFrame的排序
创建一个8*5的DataFrame
df1=DataFrame(np.random.randn(40).reshape(8,5),columns=['A','B','C','D','E'])
df1
A B C D E
0 0.059731 0.402621 0.956170 -0.388687 -0.105760
1 1.035915 2.243648 -0.254861 1.232663 -0.515500
2 -0.886092 0.464245 -1.320041 1.990206 -0.692941
3 0.782619 0.434657 -0.289410 0.320168 1.791259
4 -0.671614 -0.240356 0.226990 -0.118976 -1.103442
5 -0.844480 -0.688514 -0.077327 -0.930045 -0.483319
6 0.302611 0.696382 1.035833 0.163598 -0.464047
7 0.419607 0.808939 0.080413 -0.409038 0.037719
通过第一种方法,按照第A列进行排序,但是只得到一个Series
df1['A'].sort_values()
2 -0.886092
5 -0.844480
4 -0.671614
0 0.059731
6 0.302611
7 0.419607
3 0.782619
1 1.035915
Name: A, dtype: float64
通过第二种方法把DataFrame按照第A列进行排序,并得到一个DateFrame,想要降序同Series传入ascending=False
df1.sort_values('A')
A B C D E
2 -0.886092 0.464245 -1.320041 1.990206 -0.692941
5 -0.844480 -0.688514 -0.077327 -0.930045 -0.483319
4 -0.671614 -0.240356 0.226990 -0.118976 -1.103442
0 0.059731 0.402621 0.956170 -0.388687 -0.105760
6 0.302611 0.696382 1.035833 0.163598 -0.464047
7 0.419607 0.808939 0.080413 -0.409038 0.037719
3 0.782619 0.434657 -0.289410 0.320168 1.791259
1 1.035915 2.243648 -0.254861 1.232663 -0.515500
df2=df1.sort_values('A')
df2
A B C D E
2 -0.886092 0.464245 -1.320041 1.990206 -0.692941
5 -0.844480 -0.688514 -0.077327 -0.930045 -0.483319
4 -0.671614 -0.240356 0.226990 -0.118976 -1.103442
0 0.059731 0.402621 0.956170 -0.388687 -0.105760
6 0.302611 0.696382 1.035833 0.163598 -0.464047
7 0.419607 0.808939 0.080413 -0.409038 0.037719
3 0.782619 0.434657 -0.289410 0.320168 1.791259
1 1.035915 2.243648 -0.254861 1.232663 -0.515500
DataFrame的通过index来sort的方法
df2.sort_index()
A B C D E
0 0.059731 0.402621 0.956170 -0.388687 -0.105760
1 1.035915 2.243648 -0.254861 1.232663 -0.515500
2 -0.886092 0.464245 -1.320041 1.990206 -0.692941
3 0.782619 0.434657 -0.289410 0.320168 1.791259
4 -0.671614 -0.240356 0.226990 -0.118976 -1.103442
5 -0.844480 -0.688514 -0.077327 -0.930045 -0.483319
6 0.302611 0.696382 1.035833 0.163598 -0.464047
7 0.419607 0.808939 0.080413 -0.409038 0.037719