与示例 2 数据帧的逐行连接

Row-wise concat with sample 2 dataframes

我有 2 个数据帧,

df1
      col1    col2   col3
    0  ABC  XYZ123  RA100
    1  DEF  YHG753  RA200
    2  ABC  XYZ123  RA100
    3  DEF  YHG753  RA200
    4  ABC  XYZ123  RA100
    5  DEF  YHG753  RA200

df2
      col5 col6
    0  TU1  DUM1
    1  TU2  DUM2
    2  TU3  DUM3

我正在尝试 df1 的每一行与 df2 中随机选择的行连接起来。

我一直在尝试 pd.concat(frames, axis=1),但 concat 对我不起作用,因为 shape 数据帧不匹配。所以我想知道是否有更好的方法来做到这一点,而不是增加 df2 的行以使其与 df1 的行相匹配,然后执行 concat.

参考:

预期样本输出:

  col1    col2   col3  col5 col6 
0  ABC  XYZ123  RA100  TU3  DUM3
1  DEF  YHG753  RA200  TU1  DUM1
2  ABC  XYZ123  RA100  TU2  DUM2
3  DEF  YHG753  RA200  TU2  DUM2
4  ABC  XYZ123  RA100  TU3  DUM3
5  DEF  YHG753  RA200  TU1  DUM1

第一个想法是创建随机分配索引值 df2.index 的辅助列,然后使用 DataFrame.join:

#for test
np.random.seed(2002)

df = (df1.assign(id=np.random.choice(df2.index, size=len(df1)))
         .join(df2, on='id')
         .drop('id', axis=1))
print (df)
  col1    col2   col3 col5  col6
0  ABC  XYZ123  RA100  TU2  DUM2
1  DEF  YHG753  RA200  TU3  DUM3
2  ABC  XYZ123  RA100  TU1  DUM1
3  DEF  YHG753  RA200  TU2  DUM2
4  ABC  XYZ123  RA100  TU1  DUM1
5  DEF  YHG753  RA200  TU1  DUM1

另一个想法是在 DataFrame.merge 中通过 numpy 数组合并:

np.random.seed(2002)

idx = np.random.choice(df2.index, size=len(df1))
         
df = df1.merge(df2, left_on=idx, right_index=True).drop('key_0', axis=1)
print (df)
  col1    col2   col3 col5  col6
0  ABC  XYZ123  RA100  TU2  DUM2
3  DEF  YHG753  RA200  TU2  DUM2
1  DEF  YHG753  RA200  TU3  DUM3
2  ABC  XYZ123  RA100  TU1  DUM1
4  ABC  XYZ123  RA100  TU1  DUM1
5  DEF  YHG753  RA200  TU1  DUM1