Pyspark 中的别名

Alias in Pyspark

最近在看pyspark代码,经常看到alias。但我真的不 了解它的用法和含义。所以我想知道是否有人可以解释它是如何工作的 在下面的两个例子中。

df.select(from_unixtime(unix_timestamp(df.Date_col, 'yyyy-MM-dd HH:mm:ss')).alias('dt_col'))

df.select([count(when(isnan(c), c)).alias(c) for c in df.columns]).show()

Alias 继承自 SQL 语法。这是一种在查询中重命名变量的方法(例如 select)。它避免了创建一个您不选择的临时名称,并且之后必须使用 withColumnRenamed.

之类的名称重命名变量

例如,

df.select([count(when(isnan(c), c)).alias(c) for c in df.columns]).show()

确保计数操作的结果将 return 一个与 df 对象同名的新变量。否则你最终会得到名为 count(col1)... 的变量,其中 col1 是初始变量名称。

别名在执行聚合时非常有用。

同理,

df.select(from_unixtime(unix_timestamp(df.Date_col, 'yyyy-MM-dd HH:mm:ss')).alias('dt_col'))

是一种简洁的方法:

df.withColumn('dt_col', from_unixtime(unix_timestamp(df.Date_col, 'yyyy-MM-dd HH:mm:ss')).select('dt_col')