欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

Python Pandas: 快速入门指南 - 掌握数据排序和去重技巧

最编程 2024-01-15 13:08:50
...

最后一次更新日期: 2019/3/17

pandas是基于numpy的数据分析库,提供一些更易用的数据模型和大量高效的统计方法。

使用前先导入模块:
import pandas as pd
按需导入以下模块:
import numpy as np
import matplotlib.pyplot as plt

1. 直接与间接排序

In[5]: df=pd.DataFrame([[2,'a'],[1,'c'],[3,'b']],columns=['col1','col2'],index=[3,2,1])

In[6]: df
Out[6]: 
   col1 col2
3     2    a
2     1    c
1     3    b

In[7]: df.sort_index()
Out[7]: 
   col1 col2
1     3    b
2     1    c
3     2    a

In[8]: df.sort_values('col1')
Out[8]: 
   col1 col2
2     1    c
3     2    a
1     3    b

In [21]: df.loc[df['col2'].sort_values().index]
Out[21]: 
   col1 col2
3     2    a
1     3    b
2     1    c

sort_index方法可以按索引排序,axis参数指定排序的轴,默认0,level参数指定用于排序的多级索引的级别,默认None,ascending参数指定是否升序,默认True。

sort_values方法可以按指定键排序,by参数指定用于排序的键,axis参数指定排序的轴,默认0,ascending参数指定是否升序,默认True。

间接排序可通过loc方法传入排序后的标签索引实现,排序前两个数据模型的索引必须一致;iloc方法类似,需要传入经过numpy的argsort方法排序后的位置索引。

2. 去重

In[8]: df=pd.DataFrame({'a':[1,2,2,2],'b':[3,3,4,4]})

In[10]: df
Out[10]: 
   a  b
0  1  3
1  2  3
2  2  4
3  2  4

In[11]: df.duplicated()
Out[11]: 
0    False
1    False
2    False
3     True
dtype: bool

In[12]: df.drop_duplicates()
Out[12]: 
   a  b
0  1  3
1  2  3
2  2  4

In[14]: df.drop_duplicates('a',keep='last')
Out[14]: 
   a  b
0  1  3
3  2  4

duplicated方法用于返回标识去重结果的一维布尔数组,保留的项为True。subset参数指定参与去重的行或列标签,默认使用所有列;keep参数指定保留方式,'first'表示保留第一项,'last'表示保留最后一项,None表示不保留。

drop_duplicates方法用于返回去重结果。subsetkeep参数的作用和duplicated一样。