【问题标题】:Add columns to dataframe that not exist in df1 but exist in df2 [closed]将列添加到 df1 中不存在但存在于 df2 中的数据框 [关闭]
【发布时间】:2019-03-26 07:02:34
【问题描述】:

我想在 dataframe1(df1) 中添加 dataframe2(df2) 中不存在的列,并从 df2 中获取值。 例如

df1:

A |B |C |
---------
ad|bd|cd|
ss|tt|yy|


df2: (only 1 row)
A|B|C|D|E|F|G|
--------------
a|b|c|d|e|f|g|

我想要这个:

df3:
A|B|C|D |E|F|G|
--------------
ad|bd|cd|d|e|f|g|
ss|tt|yy|d|e|f|g|

我怎样才能快速做到?

谢谢

【问题讨论】:

    标签: apache-spark dataframe pyspark


    【解决方案1】:

    假设df2 正好有1 行,您可以使用crossJoin,如下所示:

    >>> df1.show()
    +---+---+---+
    |  A|  B|  C|
    +---+---+---+
    | ad| bd| cd|
    | ss| tt| yy|
    +---+---+---+
    
    >>> df2.show()
    +---+---+---+---+---+---+---+
    |  A|  B|  C|  D|  E|  F|  G|
    +---+---+---+---+---+---+---+
    |  a|  b|  c|  d|  e|  f|  g|
    +---+---+---+---+---+---+---+
    
    >>> df3 = df1.crossJoin(df2.drop(*df1.columns))
    >>> df3.show()
    +---+---+---+---+---+---+---+
    |  A|  B|  C|  D|  E|  F|  G|
    +---+---+---+---+---+---+---+
    | ad| bd| cd|  d|  e|  f|  g|
    | ss| tt| yy|  d|  e|  f|  g|
    +---+---+---+---+---+---+---+
    

    【讨论】:

    • 另外,您可以使用df3 = df2.drop(*df1.columns)从df2中删除df1的列以减少代码。
    • @gaw 谢谢你的建议我更新了代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-06
    • 2021-07-26
    • 1970-01-01
    • 1970-01-01
    • 2021-08-27
    • 2020-10-13
    • 1970-01-01
    相关资源
    最近更新 更多