首页 > 解决方案 > 在数据框 pyspark 的多列上应用函数

问题描述

我有一个包含 30 列的数据框。但是我想专门在 3 列上应用一个函数。我做了这样的事情:

# these are the 3 columns of a dataframe df and they are of StringType
date_columns = ['date1', 'date2', 'date3']

# my function
def convert_date(x):
    if x is '':
        return ''
    else: 
        return f.expr("date_add(to_date('1899-12-30'), cast(x as int))").cast(StringType())

# Want to do something like this
for c in date_columns:
    df = df.withColumn(c, convert_date(df[c]))

这是实现这一目标的正确方法吗?也许我在这里遗漏了一些东西。

标签: apache-sparkpyspark

解决方案


推荐阅读