[英]Pandas dataframe how to remove rows conditioned on the length of rows being smaller than a number, given a unique column value?
[英]How to restrict DataFrame number of rows to the Xth unique value in certain column?
例如,我們有以下 DataFrame:
A B
1 2
1 2
2 3
3 4
4 5
4 2
我們會知道我們想要在 A 列中有 x(比如 3)個唯一值。那么所需的 output 將是:
A B
1 2
1 2
2 3
3 4
我考慮過遍歷有問題的列,通過跟蹤並獲取具有正確索引的 DataFrame 的子集來計算唯一值的數量。 我仍然是 Python 的新手,我相信會有更有效的方法來做到這一點,請分享您的解決方案。 贊賞!
您可以嘗試series.factorize
索引從 0 開始的唯一值,然后 select 是 <= n-1 的值(因為索引從 0 開始),因此也保留訂單:
n=3
df[df['A'].factorize()[0]<=n-1]
A B
0 1 2
1 1 2
2 2 3
3 3 4
您可以使用np.random.choice
到 select 唯一的 id,然后使用這些 id 到isin
行:
selected_ids = np.random.choice(df['A'].unique(), replace=False, size=3)
df[df['A'].isin(selected_ids)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.