pySpark/Python遍历dataframe列,检查条件并填充另一列

2024-06-28 15:18:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Jupyter笔记本中使用python/pySpark,并试图找出以下问题:

我有一个像

MainDate      Date1        Date2        Date3         Date4
2015-10-25    2015-09-25   2015-10-25   2015-11-25    2015-12-25
2012-07-16    2012-04-16   2012-05-16   2012-06-16    2012-07-16
2005-03-14    2005-07-14   2005-08-14   2005-09-14    2005-10-14

我需要将MainDate与每个Date1-Date4进行比较,如果MainDate==Date,那么创建一个新列REAL=Date,如果没有匹配,那么REAL=“None”,所有日期都是日期格式的,而且实际数据框的Date1到Date72,如果有匹配的话,只能有一个匹配项

最终结果:

^{pr2}$

提前谢谢


Tags: 数据nonedate格式笔记本jupyterrealpyspark
2条回答

我会使用coalesce

from pyspark.sql.functions import col, when, coalesce, lit

df = spark.createDataFrame([
    ("2015-10-25", "2015-09-25", "2015-10-25", "2015-11-25", "2015-12-25"),
    ("2012-07-16", "2012-04-16", "2012-05-16", "2012-06-16", "2012-07-16"),
    ("2005-03-14", "2005-07-14", "2005-08-14", "2005-09-14", "2005-10-14"),],
    ("MainDate", "Date1", "Date2", "Date3", "Date4")
)


df.withColumn("REAL", 
    coalesce(*[when(col(c) == col("MainDate"), lit(c)) for c in df.columns[1:]])
).show()


+     +     +     +     +     +  -+
|  MainDate|     Date1|     Date2|     Date3|     Date4| REAL|
+     +     +     +     +     +  -+
|2015-10-25|2015-09-25|2015-10-25|2015-11-25|2015-12-25|Date2|
|2012-07-16|2012-04-16|2012-05-16|2012-06-16|2012-07-16|Date4|
|2005-03-14|2005-07-14|2005-08-14|2005-09-14|2005-10-14| null|
+     +     +     +     +     +  -+

在哪里

^{pr2}$

如果有匹配项,则返回列名(lit(c)),否则返回NULL。在

这应该比udf或转换成{}快得多。在

您可以将数据帧转换为rdd,通过检查与MainDate匹配的列日期,向每行追加一个新字段:

df = spark.read.option("header", True).option("inferSchema", True).csv("test.csv")
from pyspark.sql import Row
from pyspark.sql.types import StringType

# get the list of columns you want to compare with MainDate
dates = [col for col in df.columns if col.startswith('Date')]

# for each row loop through the dates column and find the match, if nothing matches, return None
rdd = df.rdd.map(lambda row: row + Row(REAL = next((col for col in dates if row[col] == row['MainDate']), None)))

# recreate the data frame from the rdd
spark.createDataFrame(rdd, df.schema.add("REAL", StringType(), True)).show()
+          +          +          +          +          +  -+
|            MainDate|               Date1|               Date2|               Date3|               Date4| REAL|
+          +          +          +          +          +  -+
|2015-10-25 00:00:...|2015-09-25 00:00:...|2015-10-25 00:00:...|2015-11-25 00:00:...|2015-12-25 00:00:...|Date2|
|2012-07-16 00:00:...|2012-04-16 00:00:...|2012-05-16 00:00:...|2012-06-16 00:00:...|2012-07-16 00:00:...|Date4|
|2005-03-14 00:00:...|2005-07-14 00:00:...|2005-08-14 00:00:...|2005-09-14 00:00:...|2005-10-14 00:00:...| null|
+          +          +          +          +          +  -+

相关问题 更多 >