2016-03-24 14 views
7

Bir kıvılcım veri çerçevesini, bir sütundaki değerlerin bir listeye eşit olup olmadığına göre filtrelemeye çalışıyorum. Böyle bir şey yapmak istiyorum: filtered_df.a değeri ['list','of' , 'stuff'] ve a tipi array (nullable = true) olduğuSütun değeri kıvılcımdaki bir listeye eşit olup olmadığını filtrele

filtered_df = df.where(df.a == ['list','of' , 'stuff']) 

Nerede filtered_df sadece satır içerir.

cevap

4

Güncelleme: Örneğin:

from pyspark.sql.functions import array, lit 

df.where(df.a == array(*[lit(x) for x in ['list','of' , 'stuff']])) 

Orjinal cevabı:

Peki, biraz güncel sürümleri ile

Eğer değişmezleri bir array kullanabilirsiniz Bir Python toplu iş gerektirmeyen, bunu yapmak için hacky yolu, s Böyle omething:

from pyspark.sql.functions import col, lit, size 
from functools import reduce 
from operator import and_ 

def array_equal(c, an_array): 
    same_size = size(c) == len(an_array) # Check if the same size 
    # Check if all items equal 
    same_items = reduce(
     and_, 
     (c.getItem(i) == an_array[i] for i in range(len(an_array))) 
    ) 
    return and_(same_size, same_items) 

Hızlı testi:

df = sc.parallelize([ 
    (1, ['list','of' , 'stuff']), 
    (2, ['foo', 'bar']), 
    (3, ['foobar']), 
    (4, ['list','of' , 'stuff', 'and', 'foo']), 
    (5, ['a', 'list','of' , 'stuff']), 
]).toDF(['id', 'a']) 

df.where(array_equal(col('a'), ['list','of' , 'stuff'])).show() 
## +---+-----------------+ 
## | id|    a| 
## +---+-----------------+ 
## | 1|[list, of, stuff]| 
## +---+-----------------+ 
6

Bir udf oluşturabilirsiniz.

def test_in(x): 
    return x == ['list','of' , 'stuff'] 

from pyspark.sql.functions import udf 
f = udf(test_in, pyspark.sql.types.BooleanType()) 
filtered_df = df.where(f(df.a)) 
+1

olsa o biraz yavaş mı? – Luke

İlgili konular