![](/img/trans.png)
[英]pandas dataframe - remove values from a group with less than X rows
[英]drops rows in pandas dataframe if an 'id' occurs less than 2 times
我想嘗試根據 id 的出現來刪除行。
我的數據框看起來像這樣:
df.head()
>>
index id tweet_len
161660 4001 5
116708 8571 5
213433 1813 5
213449 1813 5
213450 1813 5
213455 1813 5
29295 8190 5
213457 1813 5
29293 8190 5
213461 1531 5
如果id
出現一次,我想刪除所有行。
df.groupby('id').agg('count')['tweet_len']<2
給我
id
2 False
3 False
4 False
6 False
7 False
...
9996 False
9997 False
9998 False
9999 False
10000 False
Name: tweet_len, Length: 9252, dtype: bool
但我想要索引,以便我可以從這些索引中刪除行。 我怎樣才能?
您可以使用size
進行transform
和聚合,並使用結果來索引數據幀:
df[df.groupby('id').index.transform('size').gt(1)]
index id tweet_len
2 213433 1813 5
3 213449 1813 5
4 213450 1813 5
5 213455 1813 5
6 29295 8190 5
7 213457 1813 5
8 29293 8190 5
你可以只使用duplicate
:
df[df.duplicated('id',keep=False)]
輸出:
index id tweet_len
2 213433 1813 5
3 213449 1813 5
4 213450 1813 5
5 213455 1813 5
6 29295 8190 5
7 213457 1813 5
8 29293 8190 5
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.