[英]Dataframe: Add 'inplace' a column with the cumcount() of the dates appeared in the datetime.index
[英]cumcount reverse for dataframe column
我有一個數據框列
data = {'cumcount':[0,1,2,3,0,1,2,3,4,5,0,1,2]}
df = pd.DataFrame(data)
但我希望 cumcounts 以相反的順序(圖像)
expected = {'expected':[3,2,1,0,5,4,3,2,1,0,2,1,0]}
您可以通過添加和重新排序用於排序決策的列來做到這一點。
df['flg'] = df['cumcount'].eq(0).cumsum()
df.sort_values(['flg','cumcount'], ascending=([True, False]))
cumcount flg
3 3 1
2 2 1
1 1 1
0 0 1
9 5 2
8 4 2
7 3 2
6 2 2
5 1 2
4 0 2
12 2 3
11 1 3
10 0 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.