在我的"数据"框架中,我有2列,'time_stamp'和'hour'。我想插入" time_stamp"值的"小时"列值。我不想创建一个新列,而是在'time_stamp'
中填写缺失值我要做的是将熊猫代码替换为pyspark代码:
data['time_stamp'] = data.apply(lambda x: x['hour'] if pd.isna(x['time_stamp']) else x['time_stamp'], axis=1)
类似的东西应该起作用
from pyspark.sql import functions as f
df = (df.withColumn('time_stamp',
f.expr('case when time_stamp is null then hour else timestamp'))) #added ) which you mistyped
另外,如果您不喜欢SQL:
df = df.withColumn('time_stamp', f.when(f.col('time_stamp').isNull(),f.col('hour'))).otherwise(f.col('timestamp')) # Please correct the Brackets
您也可以使用" cocere"功能。在给定的顺序中替代了由给定列的索引定义为函数输入的索引。在您的情况下,时间戳列将被丢失的小时填充。
import pyspark.sql.functions as F
data = data.withColumn('time_stamp', F.coalesce('time_stamp', 'hour')
描述函数:https://spark.apache.org/docs/3.1.1/api/python/reference/pyper/pay/pyspark.sql.functions.coalesce.coalesce.html