简体   繁体   中英

Count zero occurrences in PySpark Dataframe

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'

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|
+--------+----+----+----+----+---+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM