我創建了這個熊貓資料框:
import numpy as np
import pandas as pd
ds = {"col1":[1,2,3,2,2,2,3,4,1,0,0,0,0,0,1,2,3,5]}
df = pd.DataFrame(data=ds)
看起來像這樣:
print(df)
col1
0 1
1 2
2 3
3 2
4 2
5 2
6 3
7 4
8 1
9 0
10 0
11 0
12 0
13 0
14 1
15 2
16 3
17 5
我需要創建一個新列 ( col2
),其中包含 中值的累積計數col1
。因此,生成的資料框將如下所示:
請問有人知道怎么做嗎?
uj5u.com熱心網友回復:
恰好有一個grouby.cumcount
功能:
df['col2'] = df.groupby('col1').cumcount().add(1)
輸出:
col1 col2
0 1 1
1 2 1
2 3 1
3 2 2
4 2 3
5 2 4
6 3 2
7 4 1
8 1 2
9 0 1
10 0 2
11 0 3
12 0 4
13 0 5
14 1 3
15 2 5
16 3 3
17 5 1
uj5u.com熱心網友回復:
考慮使用cumcount()
after groupby()
。添加 1
從 1 而不是 0 開始計數:
df['col2'] = df.groupby('col1').cumcount() 1
回報:
col1 col2
0 1 1
1 2 1
2 3 1
3 2 2
4 2 3
5 2 4
6 3 2
7 4 1
8 1 2
9 0 1
10 0 2
11 0 3
12 0 4
13 0 5
14 1 3
15 2 5
16 3 3
17 5 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/532439.html
上一篇:如何將文本與元素的開頭對齊
下一篇:熊貓列中按升序排序的問題