代码之家  ›  专栏  ›  技术社区  ›  stack0114106

python在分区列结果之间切换

  •  0
  • stack0114106  · 技术社区  · 5 年前

    我在Spark scala中使用以下代码来获得分区列。

    scala> val part_cols= spark.sql(" describe extended work.quality_stat ").select("col_name").as[String].collect()
    part_cols: Array[String] = Array(x_bar, p1, p5, p50, p90, p95, p99, x_id, y_id, # Partition Information, # col_name, x_id, y_id, "", # Detailed Table Information, Database, Table, Owner, Created Time, Last Access, Created By, Type, Provider, Table Properties, Location, Serde Library, InputFormat, OutputFormat, Storage Properties, Partition Provider)
    
    scala> part_cols.takeWhile( x => x.length()!= 0 ).reverse.takeWhile( x => x != "# col_name" )
    res20: Array[String] = Array(x_id, y_id)
    

    我需要用Python获得类似的输出。我很难在Python中为数组操作复制相同的代码,以获得[y_id,x_id]。

    下面是我试过的。

    >>> part_cols=spark.sql(" describe extended work.quality_stat ").select("col_name").collect()
    

    可以使用Python吗。

    0 回复  |  直到 5 年前
        1
  •  1
  •   werner    5 年前

    part_cols 问题中有一系列 rows .因此,第一步是将其转换为字符串数组。

    part_cols = spark.sql(...).select("col_name").collect()
    part_cols = [row['col_name'] for row in part_cols]
    

    现在,您感兴趣的数组部分的开始和结束可以用

    start_index = part_cols.index("# col_name") + 1
    end_index = part_cols.index('', start_index)
    

    终于 slice 可以从列表中提取,使用这两个值作为开始和结束

    part_cols[start_index:end_index]
    

    这个切片将包含这些值

    ['x_id', 'y_id']
    

    如果输出真的应该反转,切片

    part_cols[end_index-1:start_index-1:-1]
    

    将包含这些值

    ['y_id', 'x_id']