[英]Generate column of unique ID in pandas
我有一個包含三列的數據bins_x
, bins_y
, bins_y
和z
。 我希望添加一個新的unique
列,該唯一列是bins_x
和bins_y
唯一組合的種類的“索引”。 以下是我要附加的示例。
請注意,為清楚起見,我對數據框進行了排序,但是在此上下文中順序無關緊要。
import numpy as np
import pandas as pd
np.random.seed(12)
n = 1000
height = 20
width = 20
bins_x = np.random.randint(1, width, size=n)
bins_y = np.random.randint(1, height, size=n)
z = np.random.randint(1, 500, size=n)
df = pd.DataFrame({'bins_x': bins_x, 'bins_y': bins_y, 'z': z})
print(df.sort_values(['bins_x', 'bins_y'])
bins_x bins_y z unique
23 0 0 462 0
531 0 0 199 1
665 0 0 176 2
363 0 1 219 0
468 0 1 450 1
593 0 1 385 2
609 0 1 74 3
663 0 1 46 4
14 0 2 242 0
208 0 2 381 1
600 0 2 445 2
865 0 2 221 3
400 0 3 178 0
75 0 4 281 0
140 0 4 205 1
282 0 4 47 2
838 0 4 212 3
使用groupby
和cumcount
:
df['unique'] = df.groupby(['bins_x','bins_y']).cumcount()
>>> df.sort_values(['bins_x', 'bins_y']).head(10)
bins_x bins_y z unique
207 1 1 4 0
259 1 1 313 1
327 1 1 300 2
341 1 1 64 3
440 1 1 398 4
573 1 1 96 5
174 1 2 219 0
563 1 2 398 1
796 1 2 417 2
809 1 2 167 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.