有没有更好的方式找到重复的行_including_的第一个/最后一个? [英] Is there a better way to find duplicate rows _including_ the first/last?

查看:139
本文介绍了有没有更好的方式找到重复的行_including_的第一个/最后一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑熊猫数据框架:

 导入熊猫为pd 

df = pd.DataFrame ({
'a':pd.Series([1,1,1,2,3]),
'b':pd.Series(list('asdfg'))
我想返回列的重复值的所有行,一个,包括第一行或最后一行。我可以使用

  df [df ['a']。duplicated()| df ['a']。duplicateated(take_last = True)] 

有更好的方法吗? / p>

解决方案

您可以计数出现 a ,并为重复的行返回值> 1

 在[25]中:df [(df.groupby('a')。transform('count')> 1).values] 
Out [25]:
ab
0 1 a
1 1 s
2 1 d


Consider a Pandas data frame:

import pandas as pd

df = pd.DataFrame({
    'a': pd.Series([1,1,1,2,3]),
    'b': pd.Series(list('asdfg'))
})

I want to return all of the rows with duplicate values for column a, including the first or last row. I can do this with

df[df['a'].duplicated() | df['a'].duplicated(take_last=True)]

Is there a better way?

解决方案

You can count occurrences of a and return values>1 for duplicated rows.

In [25]: df[(df.groupby('a').transform('count')>1).values]
Out[25]:
   a  b
0  1  a
1  1  s
2  1  d

这篇关于有没有更好的方式找到重复的行_including_的第一个/最后一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆