user495490
user495490

Reputation: 173

Random values combination from columns, DataFrame, pandas

I have next DataFrame in pandas:

A  B
1  23
43 446
197 5
99 12
....

What I want to have is another DataFrame with the same columns A and B and random elements (0 < A_i < A_max, 0 < B_i < B_max), where every unique combination of A and B elements in some row doesn't exist in the first DataFrame.

Upvotes: 0

Views: 417

Answers (1)

pdn
pdn

Reputation: 81

If you don't care about the distribution, you can simply use uniform distribution from random.

Assuming the original DataFrame is named df and you want a random_df of the same length:

from random import random
import pandas as pd

A_max = df['A'].max()
B_max = df['B'].max()

random_df = pd.DataFrame(columns=df.columns)

i = 0
while i < range(len(df)):
    A_random = int(random() * A_max)
    B_random = int(random() * B_max)

    # Checking that the combination does not exist in the original DataFrame
    if len(df[(df['A'] == A_random) & (df['B'] == B_random)] == 0:
        i += 1
        random_df.append({'A': A_random, 'B': B_random}, ignore_index=True)

Upvotes: 1

Related Questions