TBI
TBI

Reputation: 77

How to iterate over a pandas dataframe and random number to each element of existing row

I am trying to iterate over a pandas data frame and add 4 random numbers to the end of each element in a specific column but my function appending the same random numbers to each row. It is generating random numbers each time it iterates through the rows but it's only adding the first 4 random digits it generates and then appending the same one to all the rows.

def create_cpr(df, symbol):
    for idx, row in df.iterrows():
        number = str(rand.randint(1111, 9999))
        df['SNumber'] = df['DateOfBirth'].str.replace('-', '') + symbol + number
    df = df.drop(['DateOfBirth'], axis=1)
    return df

I would like the results to be

  FirstName LastName         Email      SNumber
0     Joe    Jones  [email protected]  **27031968-8923**
1   Alice    Apple  [email protected]  **11121887-5318**

Upvotes: 1

Views: 526

Answers (1)

jezrael
jezrael

Reputation: 862641

You can generate all random numbers in np.random.randint, convert to strings and add to column, also DataFrame.pop is used for select and drop column:

def create_cpr(df, symbol):
    r = np.random.randint(1111, 9999, size=len(df)).astype(str)
    df['SNumber'] = df.pop('DateOfBirth').str.replace('-', '') + symbol + r
    return df

Upvotes: 3

Related Questions