Skip to main content
 首页 » 编程设计

python之保留 N 个第一次出现的

2025年05月04日9linjiqin

以下代码(当然)将仅保留按“日期”排序的行中第一次出现的“Item1”。关于如何保留它的任何建议,比如前 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']) 

请您参考如下方法:

您想使用 head ,在数据框本身或 on the groupby 上:

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 的 head 行为在 0.14 中发生了变化(它不像一个过滤器 - 但修改了索引),因此如果使用更早的版本,您将不得不重置索引。