使用leftjoin()连接两个数据帧df1和df2。
df1 = DataFrame(x1 = collect(1:1:10), x2 = fill(1.0,10))
Row │ x1 x2
│ Int64 Float64
─────┼────────────────
1 │ 1 1.0
2 │ 2 1.0
3 │ 3 1.0
4 │ 4 1.0
5 │ 5 1.0
6 │ 6 1.0
7 │ 7 1.0
8 │ 8 1.0
9 │ 9 1.0
10 │ 10 1.0
df2 = DataFrame(x1 = collect(1:2:10), x2 = fill(1.0,5))
Row │ x1 x2
│ Int64 Float64
─────┼────────────────
1 │ 1 1.0
2 │ 3 1.0
3 │ 5 1.0
4 │ 7 1.0
5 │ 9 1.0
out_df = leftjoin(df1,df2, on = :x1, makeunique=true)对于输出:
Row │ x1 x2 x2_1
│ Int64 Float64? Float64?
─────┼────────────────────────────
1 │ 1 1.0 1.0
2 │ 3 1.0 1.0
3 │ 5 1.0 1.0
4 │ 7 1.0 1.0
5 │ 9 1.0 1.0
6 │ 2 1.0 missing
7 │ 4 1.0 missing
8 │ 6 1.0 missing
9 │ 8 1.0 missing
10 │ 10 1.0 missing我的问题是df1是10行,df2是5行。如果您愿意并希望保留其原始索引位置,并且在将df1与df2 - df2插槽连接到df1匹配并在不匹配时插入缺失值,但仍保留输出的df1索引位置时,我将选择df1作为‘主’df:
Row │ x1 x2 x2_1
│ Int64 Float64? Float64?
─────┼────────────────────────────
1 │ 1 1.0 1.0
2 │ 2 1.0 missing
3 │ 3 1.0 1.0
4 │ 4 1.0 missing
5 │ 5 1.0 1.0
6 │ 6 1.0 missing
7 │ 7 1.0 1.0
8 │ 8 1.0 missing
9 │ 9 1.0 1.0
10 │ 10 1.0 missing我怎么能做到这一点呢?
发布于 2021-06-22 14:58:31
这是我们计划在未来添加的功能,请参阅https://github.com/JuliaData/DataFrames.jl/issues/2753。
现在,在我们添加所请求的功能之前,先向左侧数据框中添加一个带有行id的列(在您的示例中已经有这样一个列:x1),并对此列的结果进行排序。
https://stackoverflow.com/questions/68076023
复制相似问题