如何使用pysp过滤数据帧中的数据

2024-03-29 10:47:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为mytable as dataframe的表,下面是这个表

[+---+----+----+----+
|  x|   y|   z|   w| 
+---+----+----+----+
|  1|   a|null|null|
|  1|null|   b|null|
|  1|null|null|   c|
|  2|   d|null|null|
|  2|null|   e|null|
|  2|null|null|   f|
+---+----+----+----+]

我想要的结果是,我们按x列分组,并将y、z、w列的结果串联起来。结果如下所示。你知道吗

[+---+----+----+-
|  x|   result|     
+---+----+----+
|  1|   a b c |
|  2|   d e f |
+---+----+---+|


Tags: dataframeasmytableresultnull
1条回答
网友
1楼 · 发布于 2024-03-29 10:47:43

希望这有帮助!你知道吗

from pyspark.sql.functions import concat_ws, collect_list, concat, coalesce, lit

#sample data
df = sc.parallelize([
    [1, 'a', None, None],
    [1, None, 'b', None],
    [1, None, None, 'c'],
    [2, 'd', None, None],
    [2, None, 'e', None],
    [2, None, None, 'f']]).\
    toDF(('x', 'y', 'z', 'w'))
df.show()

result_df = df.groupby("x").\
               agg(concat_ws(' ', collect_list(concat(*[coalesce(c, lit("")) for c in df.columns[1:]]))).
                   alias('result'))
result_df.show()

输出为:

+ -+   +
|  x|result|
+ -+   +
|  1| a b c|
|  2| d e f|
+ -+   +

样本输入:

+ -+  +  +  +
|  x|   y|   z|   w|
+ -+  +  +  +
|  1|   a|null|null|
|  1|null|   b|null|
|  1|null|null|   c|
|  2|   d|null|null|
|  2|null|   e|null|
|  2|null|null|   f|
+ -+  +  +  +

相关问题 更多 >