在循环中创建唯一ID

2024-04-20 07:40:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据集,其中一列如下。我想根据以下条件创建一个新列

我知道下面的代码将满足条件 np.where((df['col']==1),((df['col'] != df1['col'].shift(1)).astype(int).cumsum()),0)

但是如果我将代码放在某个循环中,我不希望cumsum()再次从1开始。它最终将创建重复项。我怎样才能克服这个问题

是否有可能为特定条件生成随机数??因此,如果它在循环中,我仍然会创建随机数,而不是重复数

column_name
1
0
0
1
1
1
1
0
0
1

column_name -- ID
1 -- 1
0 -- 0
0 -- 0
1 -- 2
1 -- 2
1 -- 2
1 -- 2
0 -- 0
0 -- 0
1 -- 3

Tags: 数据代码namedfshiftnpcolumncol
1条回答
网友
1楼 · 发布于 2024-04-20 07:40:24

以下是获取连续整数ID的简单方法:

# setup environment
import pandas as pd
import numpy as np
np.random.seed(13)

df = pd.DataFrame({'col': [1, 0, 0, 1, 1, 1, 1, 0, 0, 1]})

# create masks for use in later updates
msk_one = df['col'] == 1
msk_first = df['col'] != df['col'].shift()

# mark each time a new series of 1s begins with a True
df['ID'] = msk_one & msk_first

# add up the Trues to get sequential ids
df['ID'] = df['ID'].cumsum()

# drop ids on the False rows
df.loc[~msk_one, 'ID'] = 0

print(df)

#    col  ID
# 0    1   1
# 1    0   0
# 2    0   0
# 3    1   2
# 4    1   2
# 5    1   2
# 6    1   2
# 7    0   0
# 8    0   0
# 9    1   3

要将这些顺序ID转换为随机ID,可以执行以下操作:

# create conversion dict mapping from sequential to random IDS
ids = df['ID'].unique()
# ignore zeros because we want to manually map them to themselves
ids = ids[ids != 0]
random_ids = np.random.choice(ids, len(ids), replace=False)
sequential_to_random = {non_random_id: random_id for non_random_id, random_id in zip(ids, random_ids)}
sequential_to_random[0] = 0

# convert the IDs to random ints
df['ID'] = df['ID'].apply(lambda x: sequential_to_random[x])

print(df)

#    col  ID
# 0    1   2
# 1    0   0
# 2    0   0
# 3    1   1
# 4    1   1
# 5    1   1
# 6    1   1
# 7    0   0
# 8    0   0
# 9    1   3

希望这有帮助

相关问题 更多 >