【问题标题】:How can i add multiple columns to existing dataframe in pyspark aws emr?如何在 pyspark aws emr 中向现有数据框添加多列?
【发布时间】:2019-08-10 12:53:20
【问题描述】:

我有这样的数据框

Row(id='123456', name='Computer Science', class='Science')

我在数据框中有 1000 行。

现在我有了类似的功能

def parse_id(id):
    id = somestuff
    return new_id

对于每一列,我都有解析函数,例如 parse_name , parse_class

我想将这些函数应用于每个数据框行,以便它提供像 new_id、'new_name'、'new_class' 这样的新列

所以生成的数据框会像

Row(id='123456', name='Computer Science', class='Science', new_id='12345668688', new_name='Computer Science new', new_class='Science new')

我该怎么做

【问题讨论】:

    标签: python dataframe pyspark apache-spark-sql amazon-emr


    【解决方案1】:

    我建议您阅读 Spark 中的 UDF 概念,f.e.这篇博文https://changhsinlee.com/pyspark-udf/ 对概念进行了很好的描述,并提供了足够多的示例。

    对于您的问题,假设您的输入数据框位于变量 df 中,那么这段代码应该可以解决您的问题:

    import pyspark.sql.functions as f
    import pyspark.sql.types as t
    
    parse_id_udf = f.udf(parse_id, t.StringType())
    parse_name_udf = f.udf(parse_name, t.StringType())
    parse_class_udf = f.udf(parse_class, t.StringType())
    
    result_df = df.select(f.col("id"), f.col("name"), f.col("class"),
                          parse_id_udf(f.col("id")).alias("new_id"),
                          parse_name_udf(f.col("name")).alias("new_name"),
                          parse_class_udf(f.col("class")).alias("new_class"))
    

    【讨论】:

      猜你喜欢
      • 2021-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-20
      • 1970-01-01
      • 2018-06-16
      • 2021-07-09
      • 1970-01-01
      相关资源
      最近更新 更多