![](/img/trans.png)
[英]Remove rows when the occurrence of a column value in the data frame is less than a certain number using pandas/python?
[英]pandas row wise sum when when consecutive column value is less than a certain number
我有一個這樣的數據框,
df
col1 col2 col3
A 34 1
B 86 2
A 53 21
C 24 33
B 21 2
C 11 1
現在我想逐行添加 col1 和 col2 值,其中連續 col3 值小於 3,因此最終數據框看起來像,
col1 col2
A 120
A 53
C 24
B 32
我可以使用 for 循環執行此操作並將其與前一行進行比較,但執行時間會很長,尋找一些 pandas 快捷方式來最有效地執行此操作。
您可以使用cumsum
獲得連續的值<=3
塊:
s = df.col3.ge(3)
# print `s.cumsum()` and `s` to see details
df.groupby([s.cumsum(),s], as_index=False).agg({'col1':'first','col2':'sum'})
Output:
col1 col2
0 A 120
1 A 53
2 B 32
3 C 24
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.