1

I have a dataframe like

+----+----------+
|id  | device   |
+----+----------+
| 123| phone    |
| 124| phone    |
| 555| phone    |
| 898| tablet   |
| 999| tablet   |
|1111| tv       |
+----+----------+

and I'm looking to get a new columns with devices value associate by an id like

+----+----------+--------------+
|id  | device   | device_id    |
+----+----------+--------------+
| 123| phone    | phone_00001  |
| 124| phone    | phone_00002  |
| 555| phone    | phone_00003  |
| 898| tablet   | tablet_00001 |
| 999| tablet   | tablet_00002 |
|1111| tv       | tv_00001     |
+----+----------+--------------+

in R it would look like

df %>% group_by(device) %>% mutate(device_id = paste0(device, '_', sprintf("%04d", row_number()) 

I'm looking for the same in pyspark.

1 Answer 1

1

A similar approach as in R, where you assign row numbers based on device partitions, and use format_string to get the desired output format:

from pyspark.sql import functions as F, Window

df2 = df.withColumn(
    'device_id', 
    F.format_string(
        '%s_%05d', 
        F.col('device'), 
        F.row_number().over(Window.partitionBy('device').orderBy('id'))
    )
)

df2.show()
+----+------+------------+
|  id|device|   device_id|
+----+------+------------+
| 123| phone| phone_00001|
| 124| phone| phone_00002|
| 555| phone| phone_00003|
|1111|    tv|    tv_00001|
| 898|tablet|tablet_00001|
| 999|tablet|tablet_00002|
+----+------+------------+
Sign up to request clarification or add additional context in comments.

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.