在 python 中,在找到新的 id# 之前,如何将计数为 0 的值取消堆叠?
In python how can I unstack values counting 0 to the end until new id# is found?
a = []
for i in range(10):
a.append((str(i) + 'b'))
a.append((str(i +2) + 'b'))
a.append((str(i +3) + 'b'))
a.append((str(i +4) + 'b'))
df = pd.DataFrame(a)
df.value_counts()
输出:
[4b 4
5b 4
9b 4
8b 4
6b 4
7b 4
3b 3
11b 3
10b 3
2b 2
12b 2
13b 1
0b 1
1b 1
到>>>>
4b 1
4b 2
4b 3
4b 4
5b 1
5b 2
5b 3
5b 4
3b 1
3b 2
3b 3
等等
IIUC,通过使用 cumcount
df['cnt']=df.groupby(0).cumcount()+1
df.sort_values([0,'cnt'],inplace=True)
a = []
for i in range(10):
a.append((str(i) + 'b'))
a.append((str(i +2) + 'b'))
a.append((str(i +3) + 'b'))
a.append((str(i +4) + 'b'))
df = pd.DataFrame(a)
df.value_counts()
输出: [4b 4 5b 4 9b 4 8b 4 6b 4 7b 4 3b 3 11b 3 10b 3 2b 2 12b 2 13b 1 0b 1 1b 1
到>>>> 4b 1 4b 2 4b 3 4b 4 5b 1 5b 2 5b 3 5b 4 3b 1 3b 2 3b 3 等等
IIUC,通过使用 cumcount
df['cnt']=df.groupby(0).cumcount()+1
df.sort_values([0,'cnt'],inplace=True)