Pandas统计重复的列里面的值方法

yipeiwu_com6年前Python基础

pandas

代码如下:

import pandas as pd
import numpy as np

salaries = pd.DataFrame({
 'name': ['BOSS', 'Lilei', 'Lilei', 'Han', 'BOSS', 'BOSS', 'Han', 'BOSS'],
 'Year': [2016, 2016, 2016, 2016, 2017, 2017, 2017, 2017],
 'Salary': [1, 2, 3, 4, 5, 6, 7, 8],
 'Bonus': [2, 2, 2, 2, 3, 4, 5, 6]
})
print(salaries)
print(salaries['Bonus'].duplicated(keep='first'))
print(salaries[salaries['Bonus'].duplicated(keep='first')].index)
print(salaries[salaries['Bonus'].duplicated(keep='first')])
print(salaries['Bonus'].duplicated(keep='last'))
print(salaries[salaries['Bonus'].duplicated(keep='last')].index)
print(salaries[salaries['Bonus'].duplicated(keep='last')])

输出如下:

 Bonus Salary Year name
0  2  1 2016 BOSS
1  2  2 2016 Lilei
2  2  3 2016 Lilei
3  2  4 2016 Han
4  3  5 2017 BOSS
5  4  6 2017 BOSS
6  5  7 2017 Han
7  6  8 2017 BOSS
0 False
1  True
2  True
3  True
4 False
5 False
6 False
7 False
Name: Bonus, dtype: bool
Int64Index([1, 2, 3], dtype='int64')
 Bonus Salary Year name
1  2  2 2016 Lilei
2  2  3 2016 Lilei
3  2  4 2016 Han
0  True
1  True
2  True
3 False
4 False
5 False
6 False
7 False
Name: Bonus, dtype: bool
Int64Index([0, 1, 2], dtype='int64')
 Bonus Salary Year name
0  2  1 2016 BOSS
1  2  2 2016 Lilei
2  2  3 2016 Lilei

非pandas

对于如nunpy中的这些操作主要如下:

假设有数组

a = np.array([1, 2, 1, 3, 3, 3, 0])

想找出 [1 3]

则有

方法1

m = np.zeros_like(a, dtype=bool)
m[np.unique(a, return_index=True)[1]] = True
a[~m]
方法2

a[~np.in1d(np.arange(len(a)), np.unique(a, return_index=True)[1], assume_unique=True)]
方法3

np.setxor1d(a, np.unique(a), assume_unique=True)
方法4

u, i = np.unique(a, return_inverse=True)
u[np.bincount(i) > 1]
方法5

s = np.sort(a, axis=None)
s[:-1][s[1:] == s[:-1]]

参考:https://stackoverflow.com/questions/11528078/determining-duplicate-values-in-an-array

以上这篇Pandas统计重复的列里面的值方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python2.x利用commands模块执行Linux shell命令

用Python写运维脚本时,经常需要执行linux shell的命令,Python中的commands模块专门用于调用Linux shell命令,并返回状态和结果,下面是commands...

python 3.5下xadmin的使用及修复源码bug

python 3.5下xadmin的使用及修复源码bug

前言 xadmin是一个django的管理后台实现,使用了更加灵活的架构设计及Bootstrap UI框架, 目的是替换现有的admin,国人开发,有许多新的特性:  &nb...

浅谈使用Python内置函数getattr实现分发模式

本文研究的主要是使用Python内置函数getattr实现分发模式的相关问题,具体介绍如下。 getattr 常见的使用模式是作为一个分发者。举个例子,如果你有一个程序可以以不同的格式输...

python计算文本文件行数的方法

本文实例讲述了python计算文本文件行数的方法。分享给大家供大家参考。具体实现方法如下: filename = "somefile.txt" myfile = open(file...

Python使用base64模块进行二进制数据编码详解

前言 昨天团队的学妹来问关于POP3协议的问题,所以今天稍稍研究了下POP3协议的格式和Python里面的poplib。而POP服务器往回传的数据里有一部分需要用到Base64进行解码,...