【问题标题】:pyspark dataframe withColumn command not working带有Column命令的pyspark数据框不起作用
【发布时间】:2020-10-25 17:21:52
【问题描述】:

我有一个输入数据框:df_input(更新的 df_input)

|comment|inp_col|inp_val|
|11     |a      |a1     |
|12     |a      |a2     |
|15     |b      |b3     |
|16     |b      |b4     |
|17     |c      |&b     |
|17     |c      |c5     |
|17     |d      |&c     |
|17     |d      |d6     |
|17     |e      |&d     |
|17     |e      |e7     |

我想将 inp_val 列中的变量替换为其值。我已尝试使用以下代码创建一个新列。

获取以'&'开头的值列表

df_new = df_inp.select(inp_val).where(df.inp_val.substr(0, 1) == '&')

现在我正在遍历列表以将“&”列值数据替换为原始列表。

for a in [row[inp_val] for row in df_new.collect()]
   df_inp = df_inp.withColumn
                 (
                   'new_col', 
                   when(df.inp_val.substr(0, 1) == '&', 
                   [row[inp_val] for row in df.select(df.inp_val).where(df.inp_col == a[1:]).collect()])
                   .otherwise(df.inp_val)
                 )

但是,我收到如下错误:

Java.lang.RuntimeException: Unsupported literal tpe class java.util.ArrayList [[5], [6]]

基本上我想要如下的输出。 请检查并告诉我错误在哪里???。 我在想我试图按照上面的代码插入两种类型的数据类型值??

更新的代码行:

tst_1 = tst.withColumn("col3_extract", when(tst.col3.substr(0, 1) == '&', regexp_replace(tst.col3, "&", "")).otherwise(""))
# Select which values need to be replaced; withColumnRenamed will also solve spark self join issues
# The substring search can also be done using regex function
tst_filter=tst.where(~F.col('col3').contains('&')).withColumnRenamed('col2','col2_collect')
# For the selected data, perform a collect list
tst_clct = tst_filter.groupby('col2_collect').agg(F.collect_list('col3').alias('col3_collect'))
#%% Join the main table with the collected list
tst_join = tst_1.join(tst_clct,on=tst_1.col3_extract==tst_clct.col2_collect,how='left').drop('col2_collect')
#%% In the column3  replace the values such as a, b
tst_result = tst_join.withColumn("result",F.when(~F.col('col3').contains('&'),F.array(F.col('col3'))).otherwise(F.col('col3_collect')))

但是,上面的代码在多次迭代中不起作用

更新的预期输出:

|comment|inp_col|inp_val|new_col                      |
|11     |a      |a1     |['a1']                       |
|12     |a      |a2     |['a2']                       |
|15     |b      |b3     |['b3']                       |
|16     |b      |b4     |['b4']                       |
|17     |c      |&b     |['b3', 'b4']                 |
|18     |c      |c5     |['c5']                       |
|19     |d      |&c     |['b3', 'b4', 'c5']           |
|20     |d      |d6     |['d6']                       |
|21     |e      |&d     |['b3', 'b4', 'c5', 'd6']     |
|22     |e      |e7     |['e7']                       |

【问题讨论】:

    标签: python dataframe pyspark hive pyspark-dataframes


    【解决方案1】:

    试试这个,self-join 和 collected list 在 rlike join condition 上是可行的方法。

    df.show() #sampledataframe
    
    #+-------+---------+---------+
    #|comment|input_col|input_val|
    #+-------+---------+---------+
    #|     11|        a|        1|
    #|     12|        a|        2|
    #|     15|        b|        5|
    #|     16|        b|        6|
    #|     17|        c|       &b|
    #|     17|        c|        7|
    #+-------+---------+---------+
    
    df.join(df.groupBy("input_col").agg(F.collect_list("input_val").alias("y1"))\
              .withColumnRenamed("input_col","x1"),F.expr("""input_val rlike x1"""),'left')\
      .withColumn("new_col", F.when(F.col("input_val").cast("int").isNotNull(), F.array("input_val"))\
                        .otherwise(F.col("y1"))).drop("x1","y1").show()
    
    #+-------+---------+---------+-------+
    #|comment|input_col|input_val|new_col|
    #+-------+---------+---------+-------+
    #|     11|        a|        1|    [1]|
    #|     12|        a|        2|    [2]|
    #|     15|        b|        5|    [5]|
    #|     16|        b|        6|    [6]|
    #|     17|        c|       &b| [5, 6]|
    #|     17|        c|        7|    [7]|
    #+-------+---------+---------+-------+
    

    【讨论】:

    • 谢谢。 @Murtihash。但是,再次感谢。但是,在 input_val 列中,我将获得 &RELAVENT_ID、MT001、MT002 等值,而不是例子。那么,我们如何修改命令来正确替换字符串值呢?
    【解决方案2】:

    您可以像这样简单地使用regex_replace:

    df.withColumn("new_col", regex_replace(col("inp_val"), "&", ""))
    

    【讨论】:

    • 谢谢@Hossein,我必须在哪里更改我的代码,是否必须在 for 循环中更改。你能用一个例子详细解释一下吗?再次感谢您。
    • 您应该更改所有代码 :)) 您选择了错误的解决方案!对数据框进行迭代是一项疯狂的工作!和关于例子!我写的代码就是一个例子。只是复制和粘贴
    • 好的,在我将 '&' 替换为 none 值后,我现在有了确切的变量。那么,如何用列表值替换它,从我需要根据变量过滤的数据框中。这就是我使用 for 循环的原因。实际上,这就是我被卡住的地方!。
    【解决方案3】:

    你能试试这个解决方案吗?你的方法可能会遇到很多问题。

    import pyspark.sql.functions as F
    from pyspark.sql.functions import col
    from pyspark.sql.window import Window
    #Test data
    tst = sqlContext.createDataFrame([(1,'a','3'),(1,'a','4'),(1,'b','5'),(1,'b','7'),(2,'c','&b'),(2,'c','&a'),(2,'d','&b')],schema=['col1','col2','col3'])
    # extract the special character out
    tst_1 = tst.withColumn("col3_extract",F.substring(F.col('col3'),2,1))
    # Selecct which values need to be replaced; withColumnRenamed will also solve spark self join issues
    # The substring search can also be done using regex function
    tst_filter=tst.where(~F.col('col3').contains('&')).withColumnRenamed('col2','col2_collect')
    # For the selected data, perform a collect list
    tst_clct = tst_filter.groupby('col2_collect').agg(F.collect_list('col3').alias('col3_collect'))
    #%% Join the main table with the collected list
    tst_join = tst_1.join(tst_clct,on=tst_1.col3_extract==tst_clct.col2_collect,how='left').drop('col2_collect')
    #%% In the column3  replace the values such as a, b
    tst_result = tst_join.withColumn("result",F.when(~F.col('col3').contains('&'),F.array(F.col('col3'))).otherwise(F.col('col3_collect')))
    

    结果:

    +----+----+----+------------+------------+------+
    |col1|col2|col3|col3_extract|col3_collect|result|
    +----+----+----+------------+------------+------+
    |   2|   c|  &a|           a|      [3, 4]|[3, 4]|
    |   2|   c|  &b|           b|      [7, 5]|[7, 5]|
    |   2|   d|  &b|           b|      [7, 5]|[7, 5]|
    |   1|   a|   3|            |        null|   [3]|
    |   1|   a|   4|            |        null|   [4]|
    |   1|   b|   5|            |        null|   [5]|
    |   1|   b|   7|            |        null|   [7]|
    +----+----+----+------------+------------+------+
    

    【讨论】:

    • 谢谢。但是,想让这个查询动态 -tst_filter=tst.where(F.col('col2').isin(['a','b'])).withColumnRenamed('col2','col2_collect' )。例如,我们动态获取列表 ['a', 'b']。既然我们不知道它只会有 ['a, 'b'] 对吧?
    • @SureshGudimetla - 我已经更新了答案,检查一下。我更专注于你被困在哪里。如何分配匹配列的一般问题可以通过多种方式完成。希望这会有所帮助
    • 再次感谢。但是,在以下命令中:tst_1 = tst.withColumn("col3_extract",F.substring(F.col('col3'),2,1))*,您已经考虑了来自2 比 1 即如果是一位数。但在 col3 列中,我将获得 &RELAVENT_ID、MT001、MT002 等值,而不是示例中的数字。那么,如何修改 substring 命令来获取字符串值呢?
    • @SureshGudimetla 您可以将值 1 替换为 1000 之类的高值。tst.withColumn("col3_extract",F.substring(F.col('col3'),2,1000)) 结果将相同.. id 值不能高达 1000 对吗?但这会更容易使用正则表达式。
    • 你是对的。我试过了,它正在工作。但是,当我们在输入数据中有多个层次结构表示时,同一行代码不起作用,结果列没有正确更新。我们必须找到解决方案??
    猜你喜欢
    • 2013-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多