【问题标题】:Dynamic Columns .withColumn Python DataFrame动态列 .withColumn Python DataFrame
【发布时间】:2020-04-21 08:55:59
【问题描述】:

我想在我的 Spark DataFrame 上动态应用 .withColumn,列名在 list

from pyspark.sql.functions import col 
from pyspark.sql.types import BooleanType

def get_dtype(dataframe,colname):
    return [dtype for name, dtype in dataframe.dtypes if name == colname][0] 
def get_matches(dataframe):
  return [x for x in dataframe.columns if get_dtype(dataframe,x)=='tinyint']

matches = get_matches(srcpartyaddressDF)
matches

上面的代码给了我列数据类型为'tinyint'的列列表

结果

Out[67]: ['verified_flag', 'standard_flag', 'overseas_flag', 'active']

现在我想对列表 matches 中的每一列动态地执行以下操作

partyaddressDF = srcpartyaddressDF.withColumn("verified_flag", col("verified_flag").cast(BooleanType())).withColumn("standard_flag", col("standard_flag").cast(BooleanType())).withColumn("overseas_flag", col("overseas_flag").cast(BooleanType())).withColumn("active", col("active").cast(BooleanType()))

如何在 Python3 中实现这一点

【问题讨论】:

    标签: python-3.x apache-spark-sql azure-databricks


    【解决方案1】:

    你可以这样做:

    # import is necessary only for python 3
    from functools import reduce
    
    def do_cast(df, cl):
        return df.withColumn(cl, col(cl).cast(BooleanType()))
    
    matches = ['verified_flag', 'standard_flag', 'overseas_flag', 'active']
    partyaddressDF = reduce(do_cast, matches, srcpartyaddressDF)
    

    基本上,它取初始值(srcpartyaddressDF),并应用列表中的第一项(列名),然后从列表中取第二个值,并将其与第一次执行时获得的结果一起使用,然后是第三个值。 ..

    【讨论】:

      猜你喜欢
      • 2017-04-18
      • 1970-01-01
      • 1970-01-01
      • 2020-10-04
      • 2018-04-16
      • 1970-01-01
      • 2017-01-29
      • 2019-03-20
      • 1970-01-01
      相关资源
      最近更新 更多