use*_*335 7 apache-spark apache-spark-sql pyspark
我有一个混合类型的数据帧.我正在使用spark.sql('select a,b,c from table')命令从hive表中读取此数据帧
.
有些列是int,bigint,double,其他列是string.共有32列.在pyspark中有什么办法可以将数据框中的所有列转换为字符串类型吗?
小智 23
只是:
from pyspark.sql.functions import col
table = spark.sql("table")
table.select([col(c).cast("string") for c in table.columns])
Run Code Online (Sandbox Code Playgroud)
这是Scala中的单行解决方案:
df.select(df.columns.map(c => col(c).cast(StringType)) : _*)
Run Code Online (Sandbox Code Playgroud)
让我们在这里看一个例子:
import org.apache.spark.sql._
import org.apache.spark.sql.types._
import org.apache.spark.sql.functions._
val data = Seq(
Row(1, "a"),
Row(5, "z")
)
val schema = StructType(
List(
StructField("num", IntegerType, true),
StructField("letter", StringType, true)
)
)
val df = spark.createDataFrame(
spark.sparkContext.parallelize(data),
schema
)
df.printSchema
//root
//|-- num: integer (nullable = true)
//|-- letter: string (nullable = true)
val newDf = df.select(df.columns.map(c => col(c).cast(StringType)) : _*)
newDf.printSchema
//root
//|-- num: string (nullable = true)
//|-- letter: string (nullable = true)
Run Code Online (Sandbox Code Playgroud)
希望对您有所帮助
| 归档时间: |
|
| 查看次数: |
15878 次 |
| 最近记录: |