有条件合并阵列

发布于 2025-02-05 16:17:13 字数 421 浏览 5 评论 0原文

我有这样的数据框:

column_1   column_2    column_3
   [1,3]        [2]           2
 [1,2,3]       null           1 
   [3,4]        [6]           1

如果不是null和del column_2,我想将列_2的值附加到column_1。

所需的输出:

column_1    column_3
 [1,3,2]           2
 [1,2,3]           1
 [3,4,6]           1

I have dataframe like this:

column_1   column_2    column_3
   [1,3]        [2]           2
 [1,2,3]       null           1 
   [3,4]        [6]           1

I want to append the value of column_2 to column_1 if it's not null and del column_2.

Desired output:

column_1    column_3
 [1,3,2]           2
 [1,2,3]           1
 [3,4,6]           1

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

总攻大人 2025-02-12 16:17:13
  • 如果列_2为null,请返回column_1
  • 否则,使用column_2使用array_union union column_1
from pyspark.sql import functions as F
df = spark.createDataFrame(
    [([1,3], [2], 2),
     ([1,2,3], None, 1),
     ([3,4], [6], 1)],
    ['column_1', 'column_2', 'column_3']
)
df = df.select(
    F.when(F.isnull('column_2'), F.col('column_1')).otherwise(F.array_union('column_1', 'column_2')).alias('column_1'),
    'column_3'
)
df.show()
# +---------+--------+
# | column_1|column_3|
# +---------+--------+
# |[1, 3, 2]|       2|
# |[1, 2, 3]|       1|
# |[3, 4, 6]|       1|
# +---------+--------+
  • if column_2 is null, return column_1
  • otherwise, union column_1 with column_2 using array_union
from pyspark.sql import functions as F
df = spark.createDataFrame(
    [([1,3], [2], 2),
     ([1,2,3], None, 1),
     ([3,4], [6], 1)],
    ['column_1', 'column_2', 'column_3']
)
df = df.select(
    F.when(F.isnull('column_2'), F.col('column_1')).otherwise(F.array_union('column_1', 'column_2')).alias('column_1'),
    'column_3'
)
df.show()
# +---------+--------+
# | column_1|column_3|
# +---------+--------+
# |[1, 3, 2]|       2|
# |[1, 2, 3]|       1|
# |[3, 4, 6]|       1|
# +---------+--------+
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文