我有几行空格分隔的输入数据:
Name Company Start_Date End_Date
Naresh HDFC 2017-01-01 2017-03-31
Anoop ICICI 2017-05-01 2017-07-30
我需要输出为:
Naresh HDFC 2017 01
Naresh HDFC 2017 02
Naresh HDFC 2017 03
Anoop ICICI 2017 05
Anoop ICICI 2017 06
Anoop ICICI 2017 07
我已经为这些数据制作了一个文本文件,并将其放在我的hadoop集群上,我已经编写了代码,但是在获取输出时遇到了一些问题。请帮忙。我不知道如何从条目中提取月份并将它们放入范围函数中,所以我在范围函数中硬编码了一个值3。
代码:
from pyspark import SparkConf,SparkContext
from pyspark.sql import SQLContext,Row
from pyspark.sql.types import *
import datetime
sc = SparkContext()
sqlcon = SQLContext(sc)
month_map={'01':1,'02':2,'03':3,'04':4,'05':5,'06':6,'07':7,'08':8,'09':9,
'10':10,'11':11,'12':12}
def get_month(str):
return datetime.date(int(str[:4]),month_map[str[5:7]],int(str[8:10]))
def parse_line(str):
match = str.split()
return (Row(name = match[0],type = match[1],start_date =
get_month(match[2]),end_date = get_month(match[3])))
# -----------------create RDD---------------
filepath = '/user/vikasmittal/Innovacer_data.txt'
rdd1 = sc.textFile(filepath)
rdd2 =rdd1.map(parse_line)
for i in range(3):
rdd3 = rdd2.map(lambda l:(l.name,l.type,l.start_date.year,i))
print(rdd3.collect())
2条答案
按热度按时间lb3vh1jj1#
加载数据后,将其转换为Dataframe并强制转换
Start_Date
以及End_Date
作为日期使用to_date
或者cast("date")
```import pyspark.sql.functions as psf
df = sqlcon
.createDataFrame(rdd2, ['Name', 'Company', 'Start_Date', 'End_Date'])
.withColumn("Start_Date", psf.to_date("Start_Date"))
.withColumn("End_Date", psf.to_date("End_Date"))
df.show()
+------+-------+----------+----------+
| Name|Company|Start_Date| End_Date|
+------+-------+----------+----------+
|Naresh| HDFC|2017-01-01|2017-03-31|
| Anoop| ICICI|2017-05-01|2017-07-30|
+------+-------+----------+----------+
from dateutil.relativedelta import relativedelta
def month_range(d1, d2):
return [d1 + relativedelta(months=+x) for x in range((d2.year - d1.year)*12 + d2.month - d1.month + 1)]
import pyspark.sql.functions as psf
from pyspark.sql.types import *
month_range_udf = psf.udf(month_range, ArrayType(DateType()))
df = df.withColumn("Date", psf.explode(month_range_udf("Start_Date", "End_Date")))
df.show()
res = df.select(
"Name",
"Company",
psf.year("Date").alias("year"),
psf.month("Date").alias("month")
)
res.show()
xuo3flqw2#
你可以用Pypark的
to_date
功能如此处所述。只需导入pyspark.sql.functions*
您可以按如下方式提取月份: