I have the following column in a pyspark dataframe, of type Array[Int].
+--------------------+
| feature_indices|
+--------------------+
| [0]|
|[0, 1, 4, 10, 11,...|
| [0, 1, 2]|
| [1]|
| [0]|
+--------------------+
I am trying to pad the array with zeros, and then limit the list length, so that the length of each row's array would be the same. For example, for n = 5, I expect:
+--------------------+
| feature_indices|
+--------------------+
| [0, 0, 0, 0, 0]|
| [0, 1, 4, 10, 11]|
| [0, 1, 2, 0, 0]|
| [1, 0, 0, 0, 0]|
| [0, 0, 0, 0, 0]|
+--------------------+
Any suggestions? I looked at pyspark rpad function, but it only operates on string type columns.
You can write a udf to do this:
from pyspark.sql.types import ArrayType, IntegerType
import pyspark.sql.functions as F
pad_fix_length = F.udf(
lambda arr: arr[:5] + [0] * (5 - len(arr[:5])),
ArrayType(IntegerType())
)
df.withColumn('feature_indices', pad_fix_length(df.feature_indices)).show()
+-----------------+
| feature_indices|
+-----------------+
| [0, 0, 0, 0, 0]|
|[0, 1, 4, 10, 11]|
| [0, 1, 2, 0, 0]|
| [1, 0, 0, 0, 0]|
| [0, 0, 0, 0, 0]|
+-----------------+
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With