繁体   English   中英

保持N次出现

[英]Keeping the N first occurrences of

以下代码(当然)将仅在按“日期”排序的行中仅保留“项1”的首次出现。 关于我如何保持它的任何建议,比如说前5次出现?

## Sort the dataframe by Date and keep only the earliest appearance of 'Item1'
## drop_duplicates considers the column 'Date' and keeps only first occurence

coocdates = data.sort('Date').drop_duplicates(cols=['Item1'])

您想在数据框本身或groupby上使用head

In [11]: df = pd.DataFrame([[1, 2], [1, 4], [1, 6], [2, 8]], columns=['A', 'B'])

In [12]: df
Out[12]:
   A  B
0  1  2
1  1  4
2  1  6
3  2  8

In [13]: df.head(2)  # the first two rows
Out[13]:
   A  B
0  1  2
1  1  4

In [14]: df.groupby('A').head(2)  # the first two rows in each group
Out[14]:
   A  B
0  1  2
1  1  4
3  2  8

注意:groupby头部的行为已在0.14中更改(它的行为不像过滤器-而是修改了索引),因此,如果使用早期版本,则必须重置索引。

使用groupby()nth()

根据Pandas docsnth()

如果n是一个整数,则取每个组的第n行;如果n是一个整数列表,则取行的子集。

因此,您需要做的是:

df.groupby('Date').nth([0,1,2,3,4]).reset_index(drop=False, inplace=True)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM