简体   繁体   中英

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM