【问题标题】:Nested expansion of dataframe which references other dataframes引用其他数据框的数据框的嵌套扩展
【发布时间】:2018-11-06 01:36:19
【问题描述】:

我有一个如下所示的数据框 df0:

col 1 | col 2|
  x   | df1  |
  y   | df2  |

df1 看起来像这样:

col 3 | col 4
 a    |   b
 c    |   d

df2 看起来像这样:

col 3 | col 4
 e    |   f
 g    |   h

我想扩展数据框col2 来得到这个:

col 1 | col 3| col 4
  x   | a    |   b
  x   | c    |   d
  y   | e    |   f
  y   | g    |   h

【问题讨论】:

  • @smci 左连接在哪一列?注意 col 2 是 dataFrame 变量名称的列表。
  • @coldspeed:是的,你是对的。但是您将 df1 和 df2 连接起来,然后对这些结果进行时髦的合并 df0['col1'],除了 col2 指定哪个子数据帧。
  • 对问题的 4 票赞成,但没有人对答案深信不疑?支持者,用钥匙连接是去这里的方式。看看并说服自己,任何低于此的内容都不够通用。
  • 感谢您的接受!如果我的答案也有帮助,您也可以投票赞成(点击我答案左侧“0”上方的三角形)。谢谢!

标签: python pandas dataframe join merge


【解决方案1】:

这应该是可能的,假设你有一个 DataFrames 字典,然后使用 pd.concat 并稍微做一些整理工作:

df_dict = {'df1' : df1, 'df2' : df2, ...}
pd.concat(
      [df_dict[d] for d in df['col 2']], keys=df['col 1']
   ).reset_index(level=1, drop=True).reset_index()

  col 1 col 3 col 4
0     x     a     b
1     x     c     d
2     y     e     f
3     y     g     h

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 2022-01-15
    • 2016-11-29
    • 2023-03-07
    • 1970-01-01
    相关资源
    最近更新 更多