PySpark按月对数据框进行分组

时间:2019-09-05 12:17:54

标签: python pyspark

我有一列日期和一列计数。 例如:

Date       Count: 
3/07/2010  1
2/01/2010  2
1/07/2012  5

我使用下面的代码更改了数据类型:

func =  udf (lambda x: datetime.strptime(x, '%d/%m/%Y'), DateType())
crime_mongodb_df = crime_mongodb_df.withColumn('Reported Date', func(col('Reported Date')))

然后,我想按年份对数据进行分组并找到每年的总数。我不确定如何进行分组。 我可以帮忙吗?谢谢!

1 个答案:

答案 0 :(得分:0)

我们可以使用pyspark.sql.functions中的函数来完成所有这些工作,包括非常容易地进行类型更改:)

from pyspark.sql.functions import to_date, col, year

df = spark.createDataFrame([('3/07/2012', 1), ('2/07/2010', 2), ('1/07/2010', 5)], ["Date", "Count"])

df.show()
df.printSchema()
+---------+-----+
|     Date|Count|
+---------+-----+
|3/07/2012|    1|
|2/07/2010|    2|
|1/07/2010|    5|
+---------+-----+

root
 |-- Date: string (nullable = true)
 |-- Count: long (nullable = true)

adjustedDf = df.withColumn("Date", to_date(col("Date"), "d/MM/yyyy"))\
    .withColumn('year', year("Date"))

adjustedDf.show()
+----------+-----+----+
|      Date|Count|year|
+----------+-----+----+
|2012-07-03|    1|2012|
|2010-07-02|    2|2010|
|2010-07-01|    5|2010|
+----------+-----+----+
adjustedDf.groupBy("year").sum("Count").show()

+----+----------+
|year|sum(Count)|
+----+----------+
|2010|         7|
|2012|         1|
+----+----------+
相关问题