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')))
然后,我想按年份对数据进行分组并找到每年的总数。我不确定如何进行分组。我能得到一些帮助吗?谢谢!
解决方案
我们可以使用 from 函数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|
+----+----------+
推荐阅读
- c# - google + api 中缺少 name、given_name 和 family_name json 属性获取用户信息
- react-native - 如何在 react-native 中渲染 JSON 对象中的数组
- python - 如何在 Django 模板中显示三重嵌套字典值?
- html - 如何使用css冻结html表中最右边的列?
- mysql - 仅保留表中分组列的最后两行
- python - pandas dataframe from_dict - 为键设置列名,为键值设置列名
- php - 如何在laravel中计算对象的特定属性的总和
- ios - FirebaseUI 的“使用电子邮件登录”形式未出现在我的屏幕上
- javascript - webpack 将其输出放在哪里以供 webpack 开发服务器使用?
- c# - 从 Powershell 接收数据时,ASP.NET MVC Action 的参数为空