pyspark更改dataframe某一列的数据类型
要更改Pyspark DataFrame中某一列的数据类型,可以使用withColumn方法和cast函数。
以下是更改DataFrame列数据类型的示例代码:
from pyspark.sql import SparkSession
from pyspark.sql.functions import col
# 创建SparkSession
spark = SparkSession.builder.getOrCreate()
# 创建示例DataFrame
data = [("Alice", 28, "2000-01-01"), ("Bob", 35, "1990-05-15")]
df = spark.createDataFrame(data, ["name", "age", "birthdate"])
# 查看DataFrame的数据类型
df.dtypes
# 输出:[('name', 'string'), ('age', 'bigint'), ('birthdate', 'string')]
# 更改age列的数据类型为float
df = df.withColumn("age", col("age").cast("float"))
# 查看更改后的数据类型
df.dtypes
# 输出:[('name', 'string'), ('age', 'float'), ('birthdate', 'string')]
在上面的示例中,使用withColumn方法将"age"列重新赋值给自身,并使用cast函数将其数据类型更改为"float"。最后通过dtypes方法查看更改后的数据类型。
请注意,cast函数支持的数据类型包括:"string"、"boolean"、"byte"、"short"、"integer"、"long"、"float"、"double"、"decimal"、"date"和"timestamp"
原文地址: https://www.cveoy.top/t/topic/hBBV 著作权归作者所有。请勿转载和采集!