Your logic condition is wrong. IIUC, what you want is:
import pyspark.sql.functions as f
df.filter((f.col('d')<5))\
.filter(
((f.col('col1') != f.col('col3')) |
(f.col('col2') != f.col('col4')) & (f.col('col1') == f.col('col3')))
)\
.show()
I broke the filter() step into 2 calls for readability, but you could equivalently do it in one line.
Output:
+----+----+----+----+---+
|col1|col2|col3|col4| d|
+----+----+----+----+---+
| A| xx| D| vv| 4|
| A| x| A| xx| 3|
| E| xxx| B| vv| 3|
| F|xxxx| F| vvv| 4|
| G| xxx| G| xx| 4|
+----+----+----+----+---+
Answer from pault on Stack OverflowYour logic condition is wrong. IIUC, what you want is:
import pyspark.sql.functions as f
df.filter((f.col('d')<5))\
.filter(
((f.col('col1') != f.col('col3')) |
(f.col('col2') != f.col('col4')) & (f.col('col1') == f.col('col3')))
)\
.show()
I broke the filter() step into 2 calls for readability, but you could equivalently do it in one line.
Output:
+----+----+----+----+---+
|col1|col2|col3|col4| d|
+----+----+----+----+---+
| A| xx| D| vv| 4|
| A| x| A| xx| 3|
| E| xxx| B| vv| 3|
| F|xxxx| F| vvv| 4|
| G| xxx| G| xx| 4|
+----+----+----+----+---+
You can also write like below (without pyspark.sql.functions):
df.filter('d<5 and (col1 <> col3 or (col1 = col3 and col2 <> col4))').show()
Result:
+----+----+----+----+---+
|col1|col2|col3|col4| d|
+----+----+----+----+---+
| A| xx| D| vv| 4|
| A| x| A| xx| 3|
| E| xxx| B| vv| 3|
| F|xxxx| F| vvv| 4|
| G| xxx| G| xx| 4|
+----+----+----+----+---+
Filtering multiple conditions RDD
Databricks Pyspark filter several columns with similar criteria
Panda - filter multiple columns by multiple values
Filtering list of objects on multiple conditions
Iโm trying to sort some date data I have into months. They are stored as strings, not dates as I havenโt found a way to do this using RDDs yet. I do not want to convert to a data frame. For example, I have:
Jan = a.filter(lambda x: โ2020-01โ in x).map(lambda x: (โ2020-01โ, 1))
Feb = a.filter(lambda x: โ2020-02โ in x).map(lambda x: (โ2020-02โ, 1))
March = a.filter(lambda x: โ2020-03โ in x).map(lambda x: (โ2020-03โ, 1))
Etc for all the months. I then joined all these with a union so I could group them later. However this took a very long time because of so much happening. What would be a better way to filter these so that I could group them by month later?