我一直在嘗試通過 python 函式從給定的列名中派生兩列。下面是代碼片段:
from pyspark.sql.functions import substring
def deriveCol(source_col_name, col1, col2):
df.select(source_col_name, substring(source_col_name, 1, 4).alias(col1), substring(source_col_name, 5, 2).alias(col2))
for i in col2:
if i >= "01" and i <= "03":
print("First quarter")
elif i >= "04" and i <= "06":
print("second quarter")
elif i >= "06" and i <= "09":
print("Third quarter")
else:
print("Fourth quarter")
return df.select([col1, col2]).show(10, truncate=True)
t = deriveCol("Report", "year", "month")
請看下面的輸出
Fourth quarter
Fourth quarter
---- -----
|year|month|
---- -----
|2022| 01|
|2022| 01|
|2022| 01|
|2022| 01|
|2022| 01|
|2022| 01|
|2022| 01|
|2022| 01|
|2022| 01|
|2022| 01|
---- -----
only showing top 10 rows
“報告” = 必須從中派生資料的源列。
“年”/“月” = 派生列。
我有一個用于資料庫表的列,我必須將它分成 3 個部分:“年”、“月”、“季度”。
“年”和“月”很簡單。但是找到“季度”是行不通的。執行代碼時,直接進入else并列印“第四季度”。但我可以說,我在上面借助substring()函式得出的“月份”也有來自給定年份的所有月份的日期。
注意:我需要將“季度”的輸出保存在單獨的列中。
uj5u.com熱心網友回復:
作為第一步,我創建了一個真正的日期列 out of string。有了日期列,我們可以應用方法year,month并且quarter。
def derive_col(source_col_name, col1, col2, col3):
date_col = F.to_date(source_col_name, 'yyyyMMdd')
df = df.select(
*[c for c in df.columns if c != source_col_name],
F.year(date_col).alias(col1),
F.month(date_col).alias(col2),
F.quarter(date_col).alias(col3)
)
return df
完整測驗,使用更多df引數,因為沒有它我無法使用該功能:
from pyspark.sql import functions as F
df = spark.createDataFrame([('20220101',), ('20220731',)], ['Report'])
def derive_col(df, source_col_name, col1, col2, col3):
date_col = F.to_date(source_col_name, 'yyyyMMdd')
df = df.select(
*[c for c in df.columns if c != source_col_name],
F.year(date_col).alias(col1),
F.month(date_col).alias(col2),
F.quarter(date_col).alias(col3)
)
return df
df = derive_col(df, 'Report', 'year', 'month', 'quarter')
df.show()
# ---- ----- -------
# |year|month|quarter|
# ---- ----- -------
# |2022| 1| 1|
# |2022| 7| 3|
# ---- ----- -------
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/526118.html
上一篇:ApacheSpark-執行緒“主”java.lang.NoClassDefFoundError中的例外:org/apache/hadoop/fs/FSDataInputStream
