Pandas基础-第3关:数据的基本操作——排序

任务描述

本关任务:根据编程要求,完成相关代码的编写。

相关知识

本关我们将学习处理SeriesDataFrame中的数据的基本手段,我们将会探讨Pandas最为重要的一些功能。

对索引进行排序

Seriessort_index()按索引排序,sort_values()按值排序; DataFrame也是用sort_index()sort_values()

 
 
  1. In[73]: obj = Series(range(4), index=['d','a','b','c'])
  2. In[74]: obj.sort_index()
  3. Out[74]:
  4. a 1
  5. b 2
  6. c 3
  7. d 0
  8. dtype: int64
  9. In[78]: frame = DataFrame(np.arange(8).reshape((2,4)),index=['three', 'one'],columns=['d','a','b','c'])
  10. In[79]: frame
  11. Out[79]:
  12. d a b c
  13. three 0 1 2 3
  14. one 4 5 6 7
  15. In[86]: frame.sort_index()
  16. Out[86]:
  17. d a b c
  18. one 4 5 6 7
  19. three 0 1 2 3
按行排序
 
 
  1. In[89]: frame.sort_index(axis=1, ascending=False)
  2. Out[89]:
  3. d c b a
  4. three 0 3 2 1
  5. one 4 7 6 5
按值排序

Series:

 
 
  1. In[92]: obj = Series([4, 7, -3, 2])
  2. In[94]: obj.sort_values()
  3. Out[94]:
  4. 2 -3
  5. 3 2
  6. 0 4
  7. 1 7
  8. dtype: int64

DataFrame:

 
 
  1. In[95]: frame = DataFrame({'b':[4, 7, -3, 2], 'a':[0, 1, 0, 1]})
  2. In[97]: frame.sort_values(by='b') #DataFrame必须传一个by参数表示要排序的列
  3. Out[97]:
  4. a b
  5. 2 0 -3
  6. 3 1 2
  7. 0 0 4
  8. 1 1 7
编程要求

根据提示,在右侧编辑器Begin-End处补充代码:

  • 对代码中s1进行按索引排序,并将结果存储到s2

  • 对代码中d1进行按值排序(indexf),并将结果存储到d2

测试说明

如果答案正确,则会输出True

# -*- coding: utf-8 -*-
from pandas import Series,DataFrame
import  pandas as pd
def sort_gate():
    '''
    返回值:
    s2: 一个Series类型数据
    d2: 一个DataFrame类型数据
    '''

    # s1是Series类型数据,d1是DataFrame类型数据
    s1 = Series([4, 3, 7, 2, 8], index=['z', 'y', 'j', 'i', 'e'])
    d1 = DataFrame({'e': [4, 2, 6, 1], 'f': [0, 5, 4, 2]})

    # 请在此添加代码 完成本关任务
    # ********** Begin *********#
    s2 = s1.sort_index()
    d2 = d1.sort_values(by = 'f')
    # ********** End **********#

    #返回s2,d2
    return s2,d2

猜你喜欢

转载自blog.csdn.net/Joy19981127/article/details/134758696