Richard Dixon
Richard Dixon

Reputation: 341

Adding multiple columns randomly to a dataframe from columns in another dataframe

I've looked everywhere but can't find a solution.

Let's say I have two tables:

Year
1
2
3
4

and

ID  Value
1    10
2    50
3    25
4    20
5    40

I need to pick randomly from both columns of the 2nd table to add to the first table - so if ID=3 is picked randomly as a column to add to the first table, I also add Value=25 i.e. end up with something like:

Year  ID  Value
1     3     25
2     1     10
3     1     10
4     5     40
5     2     50

Upvotes: 0

Views: 235

Answers (1)

Scott Boston
Scott Boston

Reputation: 153510

IIUC, do you want?

df_year[['ID', 'Value']] = df_id.sample(n=len(df_year), replace=True).to_numpy()

Output:

   Year  ID  Value
0     1   4     20
1     2   4     20
2     3   2     50
3     4   3     25

Upvotes: 1

Related Questions