[英]How to populate a data frame from 2 other data frames
I am trying to combine two dataframes in an specific way and creat a new dataframe, and avoid for loops.我试图以特定方式组合两个数据帧并创建一个新的数据帧,并避免循环。
Assume a dataframe 1 like,假设数据帧 1 像,
DF1
chan
1 A01
2 A02
3 A03
4 A04
and dataframe 2 is:和数据框 2 是:
DF2
Len
1 10
2 11
3 12
I need to creat the third dataframe that look like (without using for loops):我需要创建看起来像的第三个数据框(不使用 for 循环):
DF3
chan Len
1 A01 10
2 A01 11
3 A01 12
1 A02 10
2 A02 11
3 A02 12
Appreciate answers in R and/or python.欣赏 R 和/或 python 中的答案。 Thanks a lot in advance!
非常感谢!
阿德里安,试试
df3 <- expand.grid(df1$chan, df2$Len)
I think what you want to do is a cross join.我认为你想做的是交叉连接。 Several packages can help you do this like base R's
merge
function, join functions from the dplyr
package, etc. I like to use the crossing
function from the tidyr
package.有几个包可以帮助你做到这一点,比如 base R 的
merge
函数、 dplyr
包中的 join 函数等。我喜欢使用tidyr
包中的crossing
函数。
DF1 <- tibble(Chan = c("A01","A02","A03","A04"))
DF2 <- tibble(Len = 10:12)
tidyr::crossing(A, B)
# A tibble: 12 x 2
A B
<chr> <int>
1 A01 10
2 A01 11
3 A01 12
4 A02 10
5 A02 11
6 A02 12
7 A03 10
8 A03 11
9 A03 12
10 A04 10
11 A04 11
12 A04 12
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.