[英]Sum every 7 columns in PySpark dataframe
我正在使用下面的 usafacts 提供的这个 covid 数据集。 每列代表一个日期,格式为 header yyyy-MM-dd
。
我想以周为单位显示数据,从星期一开始到星期日结束。
这是我的方法:
对此方法的任何反馈将不胜感激。 谢谢!
更新 1:我认为明智的做法是先计算所有天列之间的差异,然后再将它们汇总为周数。 是否有 pandas 的.diff()
的 pyspark 等价物?
您的方法是有道理的,除了如果您保留星期一和星期日并使用它们的差异来获取每周的案例数,那么您将错过星期日和星期一之间发生的情况。 您只考虑 6 天而不是 7 天。 例如,您需要计算每个星期一与前一个星期一之间的差异。
go 的一种方法是:
from pyspark.sql import functions as f
import datetime
# A function that tells if a date is a monday
def is_monday(date):
[year, month, day] = date.split("-")
return datetime.date(int(year), int(month), int(day)).weekday() == 0
# reading the data
covid = (
spark.read
.option("header", true)
.option("inferSchema", true)
.csv("covid_confirmed_usafacts.csv")
)
dates = covid.columns[4:]
mondays = [ d for d in dates if is_monday(d) ]
cols = covid.columns[0:4]
# for each monday, we compute the difference with the previous one.
# For the first monday, we compute the diff with the first date we have.
# You may remove that first part if you don't need it.
diffs = (
[f.col(mondays[0]) - f.col(dates[0])] +
[f.col(mondays[d]) - f.col(mondays[d-1]) for d in range(1, len(mondays))]
)
# simply naming the week column with by its monday
named_diffs = [ diffs[d].alias(mondays[d]) for d in range(len(mondays)) ]
result_1 = covid.select(cols + named_diffs)
# Step 3: exploding the dataframe
result_2 = covid\
.withColumn("s", f.explode(f.array(*structs)))\
.drop(*dates)\
.select(cols + ['s.*'])
result_2.printSchema()
root
|-- countyFIPS: integer (nullable = true)
|-- County Name: string (nullable = true)
|-- State: string (nullable = true)
|-- StateFIPS: integer (nullable = true)
|-- date: string (nullable = false)
|-- value: integer (nullable = true)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.