【问题标题】:I need to create new column based on the condition of another column using pyspa我需要使用 pyspark 根据另一列的条件创建新列
【发布时间】:2021-10-02 01:11:23
【问题描述】:

我有一个数据框,我想根据条件添加新列:

应该根据类型和结果列创建我想要的数据框

这是我尝试过但无法实现的方法

df1.select(
    col("*"),
    when(col("Type")=='Trucks1', col('new_col1'),
        when(col("Type")=='Trucks2', col('new_col1'),
            when(col("Type")=='Cars1', col('new_col2'))
        )
    )
)

实现这一目标的正确方法是什么 提前致谢

【问题讨论】:

    标签: python sql pyspark


    【解决方案1】:

    您需要一个when 来为您想要的每个新列。

    df1.select(
        "Type",
        when(col("Type").isin("Trucks1", "Trucks2"), col("result")).alias("new_col1"),
        when(col("Type").isin("Cars1", "Cars2"), col("result")).alias("new_col2"),
    )
    

    【讨论】:

      【解决方案2】:

      这里有很好的例子https://sparkbyexamples.com/pyspark/pyspark-when-otherwise/

      df1.select(
          col("Type"),
          when(df1.Type == 'Trucks1').
          when(df1.Type == 'Trucks2').
          otherwise("").alias("new_col1"),
          when(df1.Type == 'Cars1').
          otherwise("").alias("new_col2"),
      )
      

      【讨论】:

        猜你喜欢
        • 2022-01-07
        • 2016-10-07
        • 2021-06-19
        • 2023-03-25
        • 2021-03-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多