本篇内容主要讲解“Pandas排序方式是什么? python中pandas排序有几种方式?”感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让我们大家一起来学习“Pandas排序方式是什么?python中pandas排序有几种方式?”吧!

Pandas排序方式是什么? python中pandas排序有几种方式?

Pandas中其实最主要的就是有支持三种排序方式:按索引标签排序,按值排序,按两种方式混合排序。

第一种:按索引排序

使用df.sort_index对索引进行排序,DataFrame.sort_index方法用于按索引层级对Pandas对象排序。

实例:

data.sort_values(by="hhxx", ascending=False) # DataFrame内容排序
data.sort_values(by=["hhxx", "p_change"], ascending=False).head() # 对内容进行排序
data.sort_index().head()
sr = data["price_change"]
sr.sort_values(ascending=False).head()#ascending=False:降序 True:升序
sr.sort_index().head()

第二种:数值排序

df.sort_values()方法用于按值对df排序。DataFrame.sort_values()方法用于按行列的值对DataFrame排序。DataFrame.sort_values()的可选参数by用于指定按哪列排序,该参数的值可以是一列或多列数据,例如:

df =pd. DataFrame({‘one’:[1,2,1,2],
‘two’:[1,3,1,2],
‘three’:[4,2,3,2]})
df. sort_values(by=’two’)
one  two  three
2     3    4
2     2    3
1     1    2
1     1    2

参数by支持列名列表

Df1[[‘one’,’two’,’ three’]] .sort_values(by=[‘one’,’two’])
one  two  three
1     1    2
1     1    2
2     2    3
2     3    4

第三种:按索引与值排序

Series还可以支持与numpy.ndarray.searchsorted()的类似操作方法叫做searchsorted()方法

通过参数by传递给DataFrame.sort_values()的字符串进行搜索排序。

最大值与最小值

Series支持nsmallest()与nlargest()方法,该方法返回N个最大值或最小值。对于数据量大的Series来说,该方法比先为整个Series排序,再调用head(n)这种方式的速度要快得多。

以上就是关于“Pandas排序方式是什么? python中pandas排序有几种方式?”的相关内容,希望对大家的学习有所帮助。

更多python相关文章请访问分类:python

【版权声明】本文图文出自大盘站@dapan.cc,转载请注明出处!