将Pandas Dataframe 与另一个 Dataframe 的单行合并并填充

dojqjjoe  于 2022-12-28  发布在  其他
关注(0)|答案(2)|浏览(118)

如果我有两个 Dataframe :

df1:

df1 = pd.DataFrame({'A':[10,20,15,30,45], 'B':[17,33,23,10,12]})

    A   B
0  10  17
1  20  33
2  15  23
3  30  10
4  45  12

df2:

df2 = pd.DataFrame({'C':['cat'], 'D':['dog'], 'E':['emu'], 'F':['frog'], 'G':['goat'], 'H':['horse'], 'I':['iguana']})

     C    D    E     F     G      H       I
0  cat  dog  emu  frog  goat  horse  iguana

如何合并这两个 Dataframe 并填充df1,从而使每一行都是df2的副本?
下面是我目前所做的工作,代码按预期工作,但如果我有数百列,那么我预计会有一个比我目前的方法简单得多的方法:

当前代码:

df1 = df1.assign(C = lambda x: df2.C[0],
                 D = lambda x: df2.D[0],
                 E = lambda x: df2.E[0],
                 F = lambda x: df2.F[0],
                 G = lambda x: df2.G[0],
                 H = lambda x: df2.H[0],
                 I = lambda x: df2.I[0])

预期输出:

A   B    C    D    E     F     G      H       I
0  10  17  cat  dog  emu  frog  goat  horse  iguana
1  20  33  cat  dog  emu  frog  goat  horse  iguana
2  15  23  cat  dog  emu  frog  goat  horse  iguana
3  30  10  cat  dog  emu  frog  goat  horse  iguana
4  45  12  cat  dog  emu  frog  goat  horse  iguana
oxf4rvwz

oxf4rvwz1#

在第一行使用DataFrame.assignSeries

df = df1.assign(**df2.iloc[0])
print (df)
    A   B    C    D    E     F     G      H       I
0  10  17  cat  dog  emu  frog  goat  horse  iguana
1  20  33  cat  dog  emu  frog  goat  horse  iguana
2  15  23  cat  dog  emu  frog  goat  horse  iguana
3  30  10  cat  dog  emu  frog  goat  horse  iguana
4  45  12  cat  dog  emu  frog  goat  horse  iguana
owfi6suc

owfi6suc2#

使用十字架merge

df1.merge(df2, how='cross')

输出:

A   B    C    D    E     F     G      H       I
0  10  17  cat  dog  emu  frog  goat  horse  iguana
1  20  33  cat  dog  emu  frog  goat  horse  iguana
2  15  23  cat  dog  emu  frog  goat  horse  iguana
3  30  10  cat  dog  emu  frog  goat  horse  iguana
4  45  12  cat  dog  emu  frog  goat  horse  iguana

相关问题