[英]Create a Unique Index from Column of Data
我有一個具有唯一記錄的 Pandas DataFrame,但我需要根據其中一列創建一個唯一鍵。 下面是示例數據和我嘗試通過遍歷數據並將計數增加一來創建第二列的嘗試。 我的計划是將兩者結合起來創建唯一的密鑰。
問題:有沒有更好的方法? 我的方法有什么缺陷?
import pandas as pd
import numpy as np
d = {'subid': {0: '327598650129611740', 1: '327598650129611740', 2: '327559921352747760', 3: '327676431535405027', 4: '327676431535405027', 5: '327676431535405027', 6: '327662567602840733', 7: '327778468325442201', 8: '327777161261272775', 9: '327777161261272775'}}
df = pd.DataFrame(d)
old_index = 0
child_no = 1
for subid, row in df.iterrows():
if subid == old_index:
df['child_no'] = child_no + 1
old_index = subid
child_no = child_no + 1
else:
child_no = 1
df['child_no'] = child_no
old_index = subid
df
subid child_no
0 327598650129611740 1
1 327598650129611740 1
2 327559921352747760 1
3 327676431535405027 1
4 327676431535405027 1
5 327676431535405027 1
6 327662567602840733 1
7 327778468325442201 1
8 327777161261272775 1
9 327777161261272775 1
想要的結果
subid child_no
0 327598650129611740 1
1 327598650129611740 2
2 327559921352747760 1
3 327676431535405027 1
4 327676431535405027 2
5 327676431535405027 3
6 327662567602840733 1
7 327778468325442201 1
8 327777161261272775 1
9 327777161261272775 2
任何幫助,將不勝感激。
您可以groupby
上“子編號”,然后通話cumcount
加1,因為它從開始0
:
In [30]:
df['child_no'] = df.groupby('subid').cumcount()+1
df
Out[30]:
subid child_no
0 327598650129611740 1
1 327598650129611740 2
2 327559921352747760 1
3 327676431535405027 1
4 327676431535405027 2
5 327676431535405027 3
6 327662567602840733 1
7 327778468325442201 1
8 327777161261272775 1
9 327777161261272775 2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.