python改变列的数据类型_PySpark SQL: 改变列的数据类型

1、使用Python的字典类型数据来构建DataFrame

from pyspark.sql.types import ArrayType, StructField, StructType, StringType, IntegerType, DecimalType

from decimal import Decimal

# List

data = [{"Category": 'Category A', "ID": 1, "Value": Decimal(12.40)},

{"Category": 'Category B', "ID": 2, "Value": Decimal(30.10)},

{"Category": 'Category C', "ID": 3, "Value": Decimal(100.01)}

]

schema = StructType([

StructField('Category', StringType(), False),

StructField('ID', IntegerType(), False),

StructField('Value', DecimalType(scale=2), True)

])

# 创建DataFrame

df = spark.createDataFrame(data, schema)

print(df.schema)

df.show()

执行以上代码,输出结果如下:

StructType(List(StructField(Category,StringType,false),StructField(ID,IntegerType,false),StructField(Value,DecimalType(10,2),true)))

+----------+---+------+

| Category| ID| Value|

+----------+---+------+

|Category A| 1| 12.40|

|Category B| 2| 30.10|

|Category C| 3|100.01|

+----------+---+------+

2、使用lit 函数增加两个常量列

from pyspark.sql.functions import lit

df1 = df.withColumn('Str_Col1', lit('1')) \

.withColumn('Str_Col2', lit('2020-08-09'))

df1.show()

print(df1.schema)

执行以上代码,输出结果如下:

+----------+---+------+--------+----------+

| Category| ID| Value|Str_Col1| Str_Col2|

+----------+---+------+--------+----------+

|Category A| 1| 12.40| 1|2020-08-09|

|Category B| 2| 30.10| 1|2020-08-09|

|Category C| 3|100.01| 1|2020-08-09|

+----------+---+------+--------+----------+

StructType(List(StructField(Category,StringType,false),StructField(ID,IntegerType,false),StructField(Value,DecimalType(10,2),true),StructField(Str_Col1,StringType,false),StructField(Str_Col2,StringType,false)))

从输出结果可以看出,当前的数据类型分别是: StringType, IntegerType, DecimalType, StringType 和 StringType

3、使用cast 函数改变列类型

可使用函数DataFrame.cast来转换数据类型。

from pyspark.sql.types import DateType

df1 = df1.withColumn("Str_Col1_Int", df1['Str_Col1'].cast('int')).drop('Str_Col1') \

.withColumn('Str_Col2_Date', df1['Str_Col2'].cast(DateType())).drop('Str_Col2')

df1.show()

print(df1.schema)

执行以上代码,输出结果如下:

+----------+---+------+------------+-------------+

| Category| ID| Value|Str_Col1_Int|Str_Col2_Date|

+----------+---+------+------------+-------------+

|Category A| 1| 12.40| 1| 2020-08-09|

|Category B| 2| 30.10| 1| 2020-08-09|

|Category C| 3|100.01| 1| 2020-08-09|

+----------+---+------+------------+-------------+

StructType(List(StructField(Category,StringType,false),StructField(ID,IntegerType,false),StructField(Value,DecimalType(10,2),true),StructField(Str_Col1_Int,IntegerType,true),StructField(Str_Col2_Date,DateType,true)))

可以看出,新增加的两列已经被转换为IntegerType和DateType。

另外,上面的代码中,cast函数的使用方式也不同:一个使用隐式类型字符串 'int',而另一个使用显式类型DateType。对于后者,需要确保导入该类。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值