簡體   English   中英

如何 select 值在表中出現超過 x 次的行?

[英]How to select rows whose value appears more than x times in the table?

我在選擇數據時遇到問題。 我有這種類型的DataFrame 我希望只留下在“日期”列中出現超過 5 次的日期的行。我使用filea.date.value_counts().loc[lambda s: s > 5]來查找應該保留的日期,但我堅持要做什么接下來做這個。你能幫我嗎?

您可以使用掩碼,例如:

good_dates = filea.date.value_counts().loc[lambda s: s > 5].index.tolist()
filtered_filea = filea[filea.data.isin(good_dates)]

您可以使用groupby_transform

out = df.loc[df.groupby('Date')['Date'].transform('size').loc[lambda x: x > 5].index]
print(out)

# Output

       Date
3  2022-1-2
4  2022-1-2
5  2022-1-2
6  2022-1-2
7  2022-1-2
8  2022-1-2

設置:

df = pd.DataFrame({'Date': ['2022-1-1']*3 + ['2022-1-2']*6 + ['2022-1-3']*4})
print(df)

# Output
        Date
0   2022-1-1
1   2022-1-1
2   2022-1-1
3   2022-1-2
4   2022-1-2
5   2022-1-2
6   2022-1-2
7   2022-1-2
8   2022-1-2
9   2022-1-3
10  2022-1-3
11  2022-1-3
12  2022-1-3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM