PySpark SQL 函數的 lit(~) 方法創建具有指定值的 Column 對象。
參數
1. col | value
填充該列的值。
返回值
Column 對象。
例子
考慮以下PySpark DataFrame:
df = spark.createDataFrame([["Alex", 20], ["Bob", 30]], ["name", "age"])
df.show()
+----+---+
|name|age|
+----+---+
|Alex| 20|
| Bob| 30|
+----+---+在 PySpark DataFrame 中創建常量列
要創建一個新的 PySpark DataFrame,其中包含 df 的 name 列以及由 True 值組成的名為 is_single 的新列:
import pyspark.sql.functions as F
df2 = df.select(F.col("name"), F.lit(True).alias("is_single"))
df2.show()
+----+---------+
|name|is_single|
+----+---------+
|Alex|     true|
| Bob|     true|
+----+---------+這裏,F.lit(True) 返回一個Column 對象,該對象具有一個名為alias(~) 的方法,用於分配標簽。
請注意,您可以使用  withColumn(~)  方法附加新的常量列:
import pyspark.sql.functions as F
df = spark.createDataFrame([["Alex", 20], ["Bob", 30]], ["name", "age"])
df_new = df.withColumn("is_single",  F.lit(True))
df_new.show()
+----+---+---------+
|name|age|is_single|
+----+---+---------+
|Alex| 20|     true|
| Bob| 30|     true|
+----+---+---------+創建一個列,其值基於 PySpark 中的條件
我們還可以使用 lit(~) 創建一個列,其值取決於某些條件:
import pyspark.sql.functions as F
col = df.when(F.col("age") <= 20, F.lit("junior")).otherwise(F.lit("senior"))
df3 = df.withColumn("status", col)
df3.show()
+----+---+------+
|name|age|status|
+----+---+------+
|Alex| 20|junior|
| Bob| 30|senior|
+----+---+------+請注意以下事項:
- 
我們使用 when(~)和otherwise(~)模式有條件地填充列的值。
- 
我們正在使用 withColumn(~)方法附加一個名為status的新列。
- 
F.lit("junior")實際上可以替換為"junior"- 這隻是為了演示lit(~)的一種用法。
相關用法
- Python PySpark SQL Functions length方法用法及代碼示例
- Python PySpark SQL Functions last方法用法及代碼示例
- Python PySpark SQL Functions lower方法用法及代碼示例
- Python PySpark SQL Functions least方法用法及代碼示例
- Python PySpark SQL Functions split方法用法及代碼示例
- Python PySpark SQL Functions repeat方法用法及代碼示例
- Python PySpark SQL Functions explode方法用法及代碼示例
- Python PySpark SQL Functions concat方法用法及代碼示例
- Python PySpark SQL Functions instr方法用法及代碼示例
- Python PySpark SQL Functions count_distinct方法用法及代碼示例
- Python PySpark SQL Functions dayofmonth方法用法及代碼示例
- Python PySpark SQL Functions date_add方法用法及代碼示例
- Python PySpark SQL Functions array方法用法及代碼示例
- Python PySpark SQL Functions concat_ws方法用法及代碼示例
- Python PySpark SQL Functions col方法用法及代碼示例
- Python PySpark SQL Functions translate方法用法及代碼示例
- Python PySpark SQL Functions dayofweek方法用法及代碼示例
- Python PySpark SQL Functions expr方法用法及代碼示例
- Python PySpark SQL Functions regexp_extract方法用法及代碼示例
- Python PySpark SQL Functions regexp_replace方法用法及代碼示例
- Python PySpark SQL Functions round方法用法及代碼示例
- Python PySpark SQL Functions countDistinct方法用法及代碼示例
- Python PySpark SQL Functions date_format方法用法及代碼示例
- Python PySpark SQL Functions collect_list方法用法及代碼示例
- Python PySpark SQL Functions upper方法用法及代碼示例
注:本文由純淨天空篩選整理自Isshin Inada大神的英文原創作品 PySpark SQL Functions | lit method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
