等价于R的group_by,filter,在Python中重复吗?

时间:2019-01-31 17:03:47

标签: python pandas

我正在将我的一些代码从R移到Python,但是,我在R上看起来很简单的东西上遇到了麻烦。我检查了SO和其他资源,但没有找到直接的解决方案

本质上,我试图理解Python中的Group_by,过滤器和重复项的等效项。

在R中-我的解决方案(这是我要在Python中复制的内容)是

df %>% group_by(Date) %>% filter(!duplicated(id))

我尝试过

 df.groupby('Date').drop_duplicates(keep='first')

但出现以下错误:

Cannot access callable attribute 'drop_duplicates' of 'DataFrameGroupBy' objects, try using the 'apply' method

样本数据集和预期输出:

id   date   rev
 1   1/1/18  20.4
 1   1/2/18  20.1
 1   1/2/18  20.01
 1   1/3/18  20.6
 2   1/1/18  16.4
 2   1/1/18  15.4
 2   1/2/18  17.5
 2   1/3/18  18.9

预期结果:

id   date  rev
1   1/1/18  20.4
1   1/2/18  20.1
1   1/3/18  20.6
2   1/1/18  16.4
2   1/2/18  17.5
2   1/3/18  18.9

1 个答案:

答案 0 :(得分:2)

这里是drop_duplicates

df.drop_duplicates(['date','id'],keep='first')
Out[985]: 
   id    date   rev
0   1  1/1/18  20.4
1   1  1/2/18  20.1
3   1  1/3/18  20.6
4   2  1/1/18  16.4
6   2  1/2/18  17.5
7   2  1/3/18  18.9

在R中也有一个呼叫

df %>% distinct(date, id)