简体   繁体   English

尝试使用具有多种条件的 pyspark 创建新列

[英]Trying to create new column using pyspark with multiple conditions

I have a dataset and in that dataset i have X and Y column我有一个数据集,在该数据集中我有 X 和 Y 列

  • X.dtype : timestamp X.dtype : 时间戳

  • Y.dtype: string Y.dtype:字符串

i want to make a Z column which has count value of unique Y column values.我想制作一个 Z 列,它具有唯一 Y 列值的计数值。 But it has to count before than the X time column for each row.但它必须在每行的 X 时间列之前计数。

example dataset :示例数据集:

X X Y
2021-09-08 2021-09-08 number1 1号
2021-09-09 2021-09-09 number2 2号
2021-09-10 2021-09-10 number2 2号
2021-09-11 2021-09-11 number3 3号
2021-09-12 2021-09-12 number2 2号
2021-09-13 2021-09-13 number2 2号
2021-09-14 2021-09-14 number3 3号

example result dataset :示例结果数据集:

X X Y Z Z
2021-09-08 2021-09-08 number1 1号 0 0
2021-09-09 2021-09-09 number2 2号 0 0
2021-09-10 2021-09-10 number2 2号 1 1
2021-09-11 2021-09-11 number3 3号 0 0
2021-09-12 2021-09-12 number2 2号 2 2
2021-09-13 2021-09-13 number2 2号 3 3
2021-09-14 2021-09-14 number3 3号 1 1

Note : The X column is not sorted on original dataset and i dont want to sort X column.注意:X 列未按原始数据集排序,我不想对 X 列进行排序。

you can do that with a row_number :你可以用row_number做到这一点:

from pyspark.sql import functions as F, Window

df.withColumn(
    "z",
    F.row_number().over(Window.partitionBy("y").orderBy("x")) - 1
).show()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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