【问题标题】:Pyspark orderBy giving incorrect results when sorting on more than one columnPyspark orderBy 在对多列进行排序时给出不正确的结果
【发布时间】:2019-11-13 02:25:14
【问题描述】:

概述:我正在尝试按多列对火花 DF 进行排序,而生成的 DF 仅按一列排序。

预期结果:在每个公司中名称按字母顺序排序的 DF。

玩具 DF:

l = [('Alice', 1,'funcompany'),
      ('Bob',5,'funcompany'),
       ('Jane',30,'Amazon'),
        ('Kenneth',2,'lameplace'),
          ('Dill',10,'funcompany'),
            ('Zeb',0,'lameplace'),
              ('Archie',50,'funcompany'),
                ('Debra',0,'funcompany'),
                  ('Vicky',24,'funcompany'),
                    ('Kanye',40,'lameplace')]

datis=sqlContext.createDataFrame(l, ['name', 'age','company'])

排序:

colss = ["name", "company"]

datis.orderBy(colss,ascending=[1,0]).show()

【问题讨论】:

  • 尝试使用布尔值列表而不是整数。不确定它是否会有所帮助。或者,只需执行orderBy(F.asc('name'), F.desc('company'))
  • 这是预期的,因为第一列中没有欺骗/关系。仅当第一列具有相同的值时才应用第二列排序。
  • @absolutelydevastated "datis.orderBy(F.asc('name'), F.asc('company')).show()" 似乎给出了同样的问题。您可以使用布尔值列表而不是整数来扩展一点吗?谢谢。
  • @jxc 只是为了确认一下,您是说不能使用“orderBy”按多列排序?
  • 不,您当然可以按多列排序,但 orderBy 列表中的第一列始终优先。如果通过比较第一列来确定顺序,则简单地忽略第二列和后面的列。您可以更改示例的前 4 行并将名称全部设置为 Alice 看看会发生什么

标签: python-3.x pyspark apache-spark-sql pyspark-sql pyspark-dataframes


【解决方案1】:

添加

import pyspark.sql.functions as F

改变

colss = ["name", "company"]
datis.orderBy(colss,ascending=[1,0]).show()

datis.orderBy(F.desc('company'), F.asc('name')).show()

给出想要的结果

【讨论】:

    【解决方案2】:

    试试下面的代码

    cols = ["name", "company"]
    datis.orderBy(cols, ascending=False)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-26
      • 2020-05-26
      • 1970-01-01
      相关资源
      最近更新 更多