Reputation: 420
How can I count the occurrences of 0s
in each PySpark Dataframe's
row?
I would like this result, note that the n0
column with the count by row:
+--------+-----+-----+----+-----+---+
|center |var1 |var2 |var3|var4 |n0 |
+--------+-----+-----+----+-----+---+
|center_a|0 |1 |0 |0 |3 |
|center_b|1 |1 |2 |4 |0 |
|center_c|1 |0 |1 |0 |2 |
+--------+-----+-----+----+-----+---+
I have tried this code, but without success.
x['n0'] = (x == 0).sum(axis=1)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-63-8a95da0a1861> in <module>()
----> 1 (x == 0).sum(axis=1)
AttributeError: 'bool' object has no attribute 'sum'
Upvotes: 0
Views: 1562
Reputation: 3419
A row-wise 0
check and sum:
from pyspark.sql import functions as F
df.withColumn("n0", sum(F.when(df[col] == 0, 1).otherwise(0) for col in df.columns)).show()
+--------+----+----+----+----+---+
| center|var1|var2|var3|var4| n0|
+--------+----+----+----+----+---+
|center_a| 0| 1| 0| 0| 3|
|center_b| 1| 1| 2| 4| 0|
|center_c| 1| 0| 1| 0| 2|
+--------+----+----+----+----+---+
Upvotes: 3