2

Assume the below table is pyspark dataframe and I want to apply filter on a column ind on multiple values. How to perform this in pyspark?

ind group people value 
John  1    5    100   
Ram   1    2    2       
John  1    10   80    
Tom   2    20   40    
Tom   1    7    10    
Anil  2    23   30    

I am trying following, but without success

filter = ['John', 'Ram']
filtered_df = df.filter("ind == filter ")
filtered_df.show()

How to achieve this in spark?

3

2 Answers 2

3

you could use the built in function isin: filtered_df = df.filter(df["ind"].isin(["John", "Ram"])

Sign up to request clarification or add additional context in comments.

Comments

2

You can use:

filter = ['John', 'Ram']
filtered_df = df.filter("ind in ('John', 'Ram') ")
filtered_df.show()

Or

filter = ['John', 'Ram']
processed_for_pyspark = ', '.join(['\'' + s + '\'' for s in filter])
filtered_df = df.filter("ind in ({}) ".format(processed_for_puspark))
filtered_df.show()

if you want to have your filters in a list. Also note that we use the single equal = instead of the double equal == to test equality in pyspark (like in SQL)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.