简体   繁体   English

从另一个数据帧中的列随机添加多个列到数据帧

[英]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 ie end up with something like:我需要从第二个表的两列中随机选择以添加到第一个表中 - 因此,如果 ID=3 被随机选择为添加到第一个表的列,我还添加 Value=25 ,即最终得到如下内容:

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

IIUC, do you want? IIUC,你想要吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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