我正在寻找一种方法来按月汇总我的数据。我想先在探视日只呆一个月。我的数据帧如下所示:
Row(visitdate = 1/1/2013,
patientid = P1_Pt1959,
amount = 200,
note = jnut,
)
我随后的目标是按访问日期分组并计算金额的总和。我试过这个:
from pyspark.sql import SparkSession
spark = SparkSession \
.builder \
.appName("Python Spark SQL basic example") \
.config("spark.some.config.option", "some-value") \
.getOrCreate()
file_path = "G:/Visit Data.csv"
patients = spark.read.csv(file_path,header = True)
patients.createOrReplaceTempView("visitdate")
sqlDF = spark.sql("SELECT visitdate,SUM(amount) as totalamount from visitdate GROUP BY visitdate")
sqlDF.show()
结果是:
visitdate|totalamount|
+----------+-----------+
| 9/1/2013| 10800.0|
|25/04/2013| 12440.0|
|27/03/2014| 16930.0|
|26/03/2015| 18560.0|
|14/05/2013| 13770.0|
|30/06/2013| 13880.0
我的目标是得到这样的东西:
visitdate|totalamount|
+----------+-----------+
|1/1/2013| 10800.0|
|1/2/2013| 12440.0|
|1/3/2013| 16930.0|
|1/4/2014| 18560.0|
|1/5/2015| 13770.0|
|1/6/2015| 13880.0|
最佳答案
您可以先formatvisitdate
然后按以下方式分组:
from pyspark.sql import functions as F
(df.withColumn('visitdate_month', F.date_format(F.col('visitdate'), '1/M/yyyy'))
.groupBy('visitdate_month')
.agg(F.sum(F.col('visitdate_month')))
)
关于python - pyspark中的每月聚合,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52565482/