[英]Apply Substring operation in Dataframe to create new column
我有這個數據框
我想根據字母的位置執行子字符串操作,這樣輸出就會像這樣
用於創建新列 i hv 使用子字符串操作
我寫了一個像下面這樣的小火花 scala 代碼
val df=data.toDF("HI")
df.show()
val df1=df.select(col("*"), substring(col("HI"), 0, 2).as("c"))
val df2=df1.select(col("*"), substring(col("HI"), 3, 4).as("d"))
val df3=df2.select(col("*"), substring(col("d"), 3, 4).as("e")).show()
現在我面臨的問題
1>我無法得到實際結果
2>即使我能設法得到結果,這種方法也是錯誤的,因為為了得到實際結果而創建了這么多額外的數據幀
有什么方法可以對單個數據幀執行多個子字符串操作並稍微優化代碼?
substring函數和withColumn應該這樣做:
import org.apache.spark.sql.functions._
val df = data.toDF("HI")
df.withColumn("c", substring(col("HI"), 0, 2))
.withColumn("d", substring(col("HI"), 3, 2))
.withColumn("e", substring(col("HI"), 5, 2))
.show()
印刷
+------+---+---+---+
| HI| c| d| e|
+------+---+---+---+
|abcdef| ab| cd| ef|
|ghijkl| gh| ij| kl|
|mnopqr| mn| op| qr|
|stuvwx| st| uv| wx|
| yz| yz| | |
+------+---+---+---+
查看Dataset.explain的輸出,三個字符串操作在一個階段一起執行,因此應該沒有性能問題:
== Physical Plan ==
*(1) Project [HI#10, substring(HI#10, 0, 2) AS c#12, substring(HI#10, 3, 2) AS d#15, substring(HI#10, 5, 2) AS e#19]
+- *(1) FileScan csv [HI#10] Batched: false, Format: CSV, Location: InMemoryFileIndex[file:/home/.../test.csv], PartitionFilters: [], PushedFilters: [], ReadSchema: struct<HI:string>
(我正在從 csv 文件中讀取輸入數據)
希望這會有所幫助,
val df= Seq("abcdef", "ghijkl", "mnopqr", "stuvwx", "yz").toDF("mainCol")
df.select(Array(col("mainCol")) ++ (0 to 4 by 2).map(i => concat(split('mainCol, "").getItem(i), split('mainCol, "").getItem(i + 1)).as(s"subColumn$i")): _*).show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.