gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:02:20 24 4
gpt4 key购买 nike

以下代码(当然)将仅保留按“日期”排序的行中第一次出现的“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 中发生了变化(它不像一个过滤器 - 但修改了索引),因此如果使用更早的版本,您将不得不重置索引。

关于python - 保留 N 个第一次出现的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24171905/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com