# 我想根据一列数据打上序号，上下相同数据打相同序号？

3 个回答
✓ 已被采纳

``````import numpy as np
import pandas as pd

df = pd.DataFrame({
'data': [11, 21, 24, 24, 24, 24, 25, 25, 26, 26, 26, 26, 23, 26, 26, 26, 26, 20, 26, 26, 26, 26],
'nums': 0,
})

df['nums'] = np.cumsum(df['data'].diff() != 0)

print(df)``````

``````    data  nums
0     11     1
1     21     2
2     24     3
3     24     3
4     24     3
5     24     3
6     25     4
7     25     4
8     26     5
9     26     5
10    26     5
11    26     5
12    23     6
13    26     7
14    26     7
15    26     7
16    26     7
17    20     8
18    26     9
19    26     9
20    26     9
21    26     9``````

``````import pandas as pd
import random
random.seed(10)
df=pd.DataFrame(
{
"Time":pd.date_range("2022-9-1 15:25:55",periods=40,freq="s"),
"postiveVol":[random.randint(20,23) for _ in range(40)]
}
)
sno=[]
temp=df.postiveVol.tolist()
for i,v in enumerate(temp):
if i==0:
sno.append(1)
elif v==temp[i-1]:
sno.append(sno[-1])
else:
sno.append(sno[-1]+1)
df["序号"]=sno
print(df)``````

``````def cacu():
df1 = {"postiveVol":[1,3,3,23,32,34,34]}
my_list = df1["postiveVol"]
my_list.sort()

if(len(my_list) <= 0):
return
pre = my_list[0]
base = 1
output = []
for v in my_list:
if(pre != v):
base +=1
output.append(base)
pre = v

print(list(zip(my_list,output)))
``````

[(1, 1), (3, 2), (3, 2), (23, 3), (32, 4), (34, 5), (34, 5)]

``````
def cacu():
df1 = {"postiveVol":[1,3,3,23,32,34,34]}
my_list = df1["postiveVol"]
my_list.sort()

swap = dict(Counter(my_list))
#print(swap)

output = []
for v in swap:
base = 1
for in_v in range(1,swap[v]+1):
#print(in_v)
output.append(in_v)
print(list(zip(my_list,output)))
#print(output)

cacu()``````

[(1, 1), (3, 1), (3, 2), (23, 1), (32, 1), (34, 1), (34, 2)]

###### 你尚未登录，登录后可以
• 和开发者交流问题的细节
• 关注并接收问题和回答的更新提醒
• 参与内容的编辑和改进，让解决方法与时俱进