Maddy6
Maddy6

Reputation: 417

Generate Random values X

I have below dataframe and want to replace Unique Id's from Column "X" with unique digit random number from specific column in pandas dataframe.

Index   X
0   12345
1   12345
2   12347
3   12348
4   12347
5   12350
6   12351

Upvotes: 1

Views: 98

Answers (2)

Quang Hoang
Quang Hoang

Reputation: 150725

Another way that works with random new ids:

# get the unique values and indexes
unique,idx = np.unique(df['ID'], return_inverse=True)

# new random key
random_keys = np.random.choice(np.arange(1_000_000, 9_999_999+1), size=len(unique), replace=False)

df['new_ID'] = random_keys[idx]

Or similar idea with factorize:

enum = df['ID'].factorize()[0]

random_keys = np.random.choice(np.arange(1_000_000, 9_999_999+1), size=enum.max()+1, replace=False)

df['new_ID'] = random_keys[enum]

Upvotes: 0

BENY
BENY

Reputation: 323226

Try with factorize

df['newid'] = df.ID.factorize()[0]+100000
Out[318]: 
array([100000, 100000, 100001, 100002, 100001, 100003, 100004],
      dtype=int64)

Upvotes: 2

Related Questions