ARRAY_CONTAINS verbose values ​​in pyspark

I work with pyspark.sql.dataframe.DataFrame. I would like to filter out rows stackon the basis of several variables, not one {val}. I am working with a Python 2 Jupyter laptop. I am currently doing the following:

stack = hiveContext.sql("""
    SELECT * 
    FROM db.table
    WHERE col_1 != ''
""")

stack.show()
+---+-------+-------+---------+
| id| col_1 | . . . | list    |
+---+-------+-------+---------+
| 1 |   524 | . . . |[1, 2]   |
| 2 |   765 | . . . |[2, 3]   |
.
.
.
| 9 |   765 | . . . |[4, 5, 8]|

for i in len(list):
    filtered_stack = stack.filter("array_contains(list, {val})".format(val=val.append(list[i])))
    (some query on filtered_stack)

How do I rewrite this in Python code to filter strings based on multiple values? those. where {val} is equal to some array of one or more elements.

My question is related to: ARRAY_CONTAINS mulls the values ​​in the hive , however I am trying to achieve the above in a Python 2 Jupyter laptop.

+4
source share
1 answer

With Python UDF:

from pyspark.sql.functions import udf, size
from pyspark.sql.types import *

intersect = lambda type: (udf(
    lambda x, y: (
        list(set(x) & set(y)) if x is not None and y is not None else None),
    ArrayType(type)))

df = sc.parallelize([([1, 2, 3], [1, 2]), ([3, 4], [5, 6])]).toDF(["xs", "ys"])

integer_intersect = intersect(IntegerType())

df.select(
    integer_intersect("xs", "ys"),
    size(integer_intersect("xs", "ys"))).show()

+----------------+----------------------+
|<lambda>(xs, ys)|size(<lambda>(xs, ys))|
+----------------+----------------------+
|          [1, 2]|                     2|
|              []|                     0|
+----------------+----------------------+

With letters:

from pyspark.sql.functions import array, lit

df.select(integer_intersect("xs", array(lit(1), lit(5)))).show()

+-------------------------+
|<lambda>(xs, array(1, 5))|
+-------------------------+
|                      [1]|
|                       []|
+-------------------------+

or

df.where(size(integer_intersect("xs", array(lit(1), lit(5)))) > 0).show()

+---------+------+
|       xs|    ys|
+---------+------+
|[1, 2, 3]|[1, 2]|
+---------+------+
+3

Source: https://habr.com/ru/post/1666185/


All Articles