【问题标题】:Scala: copying a dataframe column into array and preserving the original orderScala:将数据框列复制到数组中并保留原始顺序
【发布时间】:2019-08-22 23:50:09
【问题描述】:

假设我有一个数据框df,其中包含一个时间戳列和一个整数列,因此时间戳不会出现在超过 1 条记录中。它看起来像这样:

timestamp  | value
------------------
2019-07-03 | 2100
2019-04-15 | 1828
2019-06-01 | 948
2019-07-12 | 2912
[etc.]

使用以下我可以按时间戳排序:

df.createorReplaceView("tmp")
var sql_cmd = """select 
                    * 
                 from 
                    tmp
                 order by
                    timestamp asc""";
var new_df = spark.sql(sql_command);

然后让new_df 朝这个方向看:

timestamp  | value
------------------
2019-04-15 | 1828
2019-06-01 | 948
2019-07-03 | 2100
2019-07-12 | 2912
[etc.]

有没有办法将new_dfvalue 的内容放入数组new_df_array 中,从而保留该列的数字顺序? (即:new_df_array[0] == 1828new_df_array[1] == 948等)

【问题讨论】:

  • AFAIK,一个简单的collect() 不会改变数据框中记录的顺序。
  • @sachav 感谢您的评论 - 这太棒了!您能否指出可以确保我 collect() 不会影响数据框中的排序的文档?
  • 虽然收集肯定会维持分区内的顺序,但我不确定是否会保留分区本身的顺序。
  • 虽然我在文档中找不到任何参考资料,但这里有一个有趣的答案:stackoverflow.com/questions/33289249/…

标签: scala apache-spark


【解决方案1】:

这应该可以解决问题:

val array = new_df.coalesce(1).sortWithinPartitions($"timestamp").collect()

请注意,这不是数据帧,而是一个普通的 scala 数组

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 2020-11-20
    • 2019-08-24
    • 1970-01-01
    • 2018-11-24
    相关资源
    最近更新 更多