[संपादित: मार्च २०१६: वोटों के लिए धन्यवाद! हालांकि वास्तव में, यह सबसे अच्छा जवाब नहीं है, मुझे लगता है कि समाधान के आधार पर withColumn, withColumnRenamedऔरcast msemelman, मार्टिन Senne और दूसरों द्वारा आगे रखा सरल और क्लीनर हैं]।
मुझे लगता है कि आपका दृष्टिकोण ठीक है, याद रखें कि स्पार्क DataFrameपंक्तियों का एक (अपरिवर्तनीय) आरडीडी है, इसलिए हम कभी भी एक कॉलम की जगह नहीं ले रहे हैं , बस DataFrameहर बार एक नया स्कीमा बना रहे हैं।
मान लें कि आपके पास निम्नलिखित स्कीमा के साथ एक मूल df है:
scala> df.printSchema
root
|-- Year: string (nullable = true)
|-- Month: string (nullable = true)
|-- DayofMonth: string (nullable = true)
|-- DayOfWeek: string (nullable = true)
|-- DepDelay: string (nullable = true)
|-- Distance: string (nullable = true)
|-- CRSDepTime: string (nullable = true)
और कुछ यूडीएफ को एक या कई स्तंभों पर परिभाषित किया गया है:
import org.apache.spark.sql.functions._
val toInt = udf[Int, String]( _.toInt)
val toDouble = udf[Double, String]( _.toDouble)
val toHour = udf((t: String) => "%04d".format(t.toInt).take(2).toInt )
val days_since_nearest_holidays = udf(
(year:String, month:String, dayOfMonth:String) => year.toInt + 27 + month.toInt-12
)
स्तंभ प्रकार बदलना या किसी अन्य से नया DataFrame बनाना इस तरह लिखा जा सकता है:
val featureDf = df
.withColumn("departureDelay", toDouble(df("DepDelay")))
.withColumn("departureHour", toHour(df("CRSDepTime")))
.withColumn("dayOfWeek", toInt(df("DayOfWeek")))
.withColumn("dayOfMonth", toInt(df("DayofMonth")))
.withColumn("month", toInt(df("Month")))
.withColumn("distance", toDouble(df("Distance")))
.withColumn("nearestHoliday", days_since_nearest_holidays(
df("Year"), df("Month"), df("DayofMonth"))
)
.select("departureDelay", "departureHour", "dayOfWeek", "dayOfMonth",
"month", "distance", "nearestHoliday")
कौन सी पैदावार:
scala> df.printSchema
root
|-- departureDelay: double (nullable = true)
|-- departureHour: integer (nullable = true)
|-- dayOfWeek: integer (nullable = true)
|-- dayOfMonth: integer (nullable = true)
|-- month: integer (nullable = true)
|-- distance: double (nullable = true)
|-- nearestHoliday: integer (nullable = true)
यह आपके अपने समाधान के बहुत करीब है। बस, एस प्रकार परिवर्तन और अन्य परिवर्तनों को अलग-अलग रखने से udf valकोड अधिक पठनीय और पुन: प्रयोज्य हो जाता है।