3
df = pd.DataFrame(np.random.randint(0,6,size=(1200000, 3)), 
columns=list('ABC'))
df['sum'] = df[['A','B','C']].sum(axis=1)
df = df[df['sum']==5]
df = df.sample(n=100000)

I want to create a dataframe with three different columns with random numbers between 0 and 5 such that sum across column is 5.

2 Answers 2

2

You can use itertools permutations to find numbers between 0 and 5 with sum equal to 5 and assign the result to DataFrame

import itertools
df = pd.DataFrame([elem for elem in list(itertools.permutations(range(6), 3)) if sum(elem) == 5], columns = list('ABC'))
df['sum'] = df.sum(1)

    A   B   C   sum
0   0   1   4   5
1   0   2   3   5
2   0   3   2   5
3   0   4   1   5
4   1   0   4   5
5   1   4   0   5
6   2   0   3   5
7   2   3   0   5
8   3   0   2   5
9   3   2   0   5
10  4   0   1   5
11  4   1   0   5
Sign up to request clarification or add additional context in comments.

3 Comments

I want only 5 rows.
You can always select 5 rows randomly, df.sample(n = 5)
@Vaishali I think he want to directly create 5 row, rather than create, then select.
0

You can check with np.random.multinomial

np.random.multinomial(5, [1/3.]*3, size=5) # here when you input size 5 , it only creat 5 lines
Out[38]: 
array([[2, 2, 1],
       [1, 2, 2],
       [0, 3, 2],
       [1, 1, 3],
       [3, 1, 1]])

Finish the DataFrame

ary=np.random.multinomial(5, [1/3.]*3, size=5)

df=pd.DataFrame(ary,columns=['A','B','C'])
df['SUM']=df.sum(1)
df
Out[43]: 
   A  B  C  SUM
0  1  2  2    5
1  2  2  1    5
2  1  3  1    5
3  1  1  3    5
4  1  2  2    5

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.