【问题标题】:Creating unique ids in a loop在循环中创建唯一 ID
【发布时间】:2020-05-25 12:49:26
【问题描述】:

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

我知道下面的代码将满足条件 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

【问题讨论】:

    标签: python pandas data-science data-analysis data-transform


    【解决方案1】:

    这是获取连续 int 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
    

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2019-03-27
      • 2014-11-24
      • 1970-01-01
      • 1970-01-01
      • 2015-12-26
      • 1970-01-01
      • 1970-01-01
      • 2012-09-22
      • 2023-03-20
      相关资源
      最近更新 更多