您一次只能使用withColumn 创建一列,因此我们必须调用它多次。
# We set up the problem
columns = ["col1", "col2", "col3"]
data = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
rdd = spark.sparkContext.parallelize(data)
df = rdd.toDF(columns)
df.show()
#+----+----+----+
#|col1|col2|col3|
#+----+----+----+
#| 1| 2| 3|
#| 4| 5| 6|
#| 7| 8| 9|
#+----+----+----+
由于您的条件基于 if-else 条件,您可以使用 when 和 otherwise 在每次迭代中执行逻辑。因为我不知道你的用例,所以我检查一个简单的条件,如果colX 是偶数,我们将它添加到 col3,如果奇数,我们减去。
我们根据列名末尾的数字加上列数(在我们的例子中为 3)在每次迭代中创建一个新列,以生成 4、5、6。
# You'll need a function to extract the number at the end of the column name
import re
def get_trailing_number(s):
m = re.search(r'\d+$', s)
return int(m.group()) if m else None
from pyspark.sql.functions import col, when
from pyspark.sql.types import FloatType
rich_df = df
for i in df.columns:
rich_df = rich_df.withColumn(f'col{get_trailing_number(i) + 3}', \
when(col(i) % 2 == 0, col(i) + col("col3"))\
.otherwise(col(i) - col("col3")).cast(FloatType()))
rich_df.show()
#+----+----+----+----+----+----+
#|col1|col2|col3|col4|col5|col6|
#+----+----+----+----+----+----+
#| 1| 2| 3|-2.0| 5.0| 0.0|
#| 4| 5| 6|10.0|-1.0|12.0|
#| 7| 8| 9|-2.0|17.0| 0.0|
#+----+----+----+----+----+----+
这是函数的 UDF 版本
def func(col, constant):
if (col % 2 == 0):
return float(col + constant)
else:
return float(col - constant)
func_udf = udf(lambda col, constant: func(col, constant), FloatType())
rich_df = df
for i in df.columns:
rich_df = rich_df.withColumn(f'col{get_trailing_number(i) + 3}', \
func_udf(col(i), col("col3")))
rich_df.show()
#+----+----+----+----+----+----+
#|col1|col2|col3|col4|col5|col6|
#+----+----+----+----+----+----+
#| 1| 2| 3|-2.0| 5.0| 0.0|
#| 4| 5| 6|10.0|-1.0|12.0|
#| 7| 8| 9|-2.0|17.0| 0.0|
#+----+----+----+----+----+----+
如果不了解您要做什么,就很难说更多。