我有這樣的資料:
--- ------
| id| col|
--- ------
| 1|210927|
| 2|210928|
| 3|210929|
| 4|210930|
| 5|211001|
--- ------
我想要如下輸出:
--- ------ ----------
| id| col| t_date1|
--- ------ ----------
| 1|210927|27-09-2021|
| 2|210928|28-09-2021|
| 3|210929|29-09-2021|
| 4|210930|30-09-2021|
| 5|211001|01-10-2021|
--- ------ ----------
我能夠使用pandas和獲得它strptime。下面是我的代碼:
pDF= df.toPandas()
valuesList = pDF['col'].to_list()
modifiedList = list()
for i in valuesList:
... modifiedList.append(datetime.strptime(i, "%y%m%d").strftime('%d-%m-%Y'))
pDF['t_date1']=modifiedList
df = spark.createDataFrame(pDF)
現在,主要問題是我想avoid使用pandas,list因為我要處理millions甚至處理billions資料,而當涉及到大資料時,pandas 會減慢這個程序。
我在 spark 中嘗試了各種方法,例如unixtime, to_date,timestamp使用我需要的格式,但沒有運氣,而且由于strptime僅適用于字串,因此無法直接在列上使用它。我不愿意創建 UDF,因為它們也很慢。
主要問題是確定我無法在 spark 中實作的確切年份,但我希望僅使用 spark 來實作它。需要改變什么?我哪里錯了?
uj5u.com熱心網友回復:
您是否使用了正確的格式?使用yyMMdd和to_date進行決議dd-MM-yyyy和 date_format格式化應該可以作業:
import pyspark.sql.functions as f
df.withColumn('t_date', f.date_format(f.to_date('col', 'yyMMdd'), 'dd-MM-yyyy')).show()
--- ------ ----------
| id| col| t_date|
--- ------ ----------
| 1|210927|27-09-2021|
| 2|210928|28-09-2021|
| 3|210929|29-09-2021|
| 4|210930|30-09-2021|
| 5|211001|01-10-2021|
--- ------ ----------
如果col不是字串型別,首先轉換為字串:
df.withColumn('t_date', f.date_format(f.to_date(f.col('col').cast('string'), 'yyMMdd'), 'dd-MM-yyyy')).show()
uj5u.com熱心網友回復:
這是另一種方式:
(df.assign(t_date1 = pd.to_datetime('20' df['Col'].astype(str)
,format = '%Y/%m/%d').dt.strftime('%d-%m-%Y')))
uj5u.com熱心網友回復:
根據 Python datetime.strptime
# Open Group specification for strptime() states that a %y
#value in the range of [00, 68] is in the century 2000, while
#[69,99] is in the century 1900
if year <= 68:
year = 2000
else:
year = 1900
使用 PySparkwhen和otherwise
from pyspark.sql import functions as F
(df
.withColumn('y', F.substring('col', 0, 2).cast('int'))
.withColumn('y', F
.when(F.col('y') <= 68, F.col('y') 2000)
.otherwise(F.col('y') 1900)
)
.show()
)
# Output
# --- ------ ----
# | id| col| y|
# --- ------ ----
# | 1|210927|2021|
# | 2|910927|1991|
# --- ------ ----
從技術上講,你可以整天爭論這種方法(0-68 然后 69-99)。但它在這里是一種“標準”,所以我認為在這里使用它沒有任何問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/333424.html
