【问题标题】:How to find the size or shape of a DataFrame in PySpark?如何在 PySpark 中查找 DataFrame 的大小或形状?
【发布时间】:2017-01-31 20:12:00
【问题描述】:

我正在尝试在 PySpark 中找出 DataFrame 的大小/形状。我没有看到一个函数可以做到这一点。

在 Python 中,我可以这样做:

data.shape()

PySpark 中是否有类似的功能?这是我目前的解决方案,但我正在寻找一个元素

row_number = data.count()
column_number = len(data.dtypes)

列数的计算并不理想……

【问题讨论】:

  • 把这个放在一个函数里?
  • 您的意思是data.shape 用于 NumPy 和 Pandas? shape 不是函数。
  • 什么不理想?我不确定您还想完成什么而不是您已经拥有的(除了用 data.columns 替换 data.dtypes,但这没什么区别)。

标签: python dataframe pyspark


【解决方案1】:

您可以通过以下方式获取其shape:

print((df.count(), len(df.columns)))

【讨论】:

  • 这对于分布在节点上的较大数据集是否可以正常工作?
【解决方案2】:

使用df.count() 获取行数。

【讨论】:

    【解决方案3】:

    将此添加到您的代码中:

    import pyspark
    def spark_shape(self):
        return (self.count(), len(self.columns))
    pyspark.sql.dataframe.DataFrame.shape = spark_shape
    

    那你就可以了

    >>> df.shape()
    (10000, 10)
    

    但请提醒您,.count() 对于尚未持久化的非常大的表可能会非常慢。

    【讨论】:

      【解决方案4】:
      print((df.count(), len(df.columns)))
      

      对于较小的数据集更容易。

      但是,如果数据集很大,另一种方法是使用 pandas 和箭头将数据框转换为 pandas df 并调用 shape

      spark.conf.set("spark.sql.execution.arrow.enabled", "true")
      spark.conf.set("spark.sql.crossJoin.enabled", "true")
      print(df.toPandas().shape)
      

      【讨论】:

      • .toPandas 不是一个动作吗?意思:这不是要收集数据给你的master,然后在上面调用shape吗?如果是这样,那将是不可取的,除非你确定它会适合主人的记忆。
      • 如果数据集很大,收集到 Pandas 正是你不想做的事情。顺便说一句:你为​​什么要为此启用交叉连接?箭头配置是否有助于收集到熊猫?
      【解决方案5】:

      我认为 Spark 中没有类似 data.shape 的功能。但我会使用len(data.columns) 而不是len(data.dtypes)

      【讨论】:

      • 这只是给你列数。行数呢?
      【解决方案6】:

      我已经使用这个代码块解决了这个问题。请尝试一下,它有效。

      import pyspark
      def sparkShape(dataFrame):
          return (dataFrame.count(), len(dataFrame.columns))
      pyspark.sql.dataframe.DataFrame.shape = sparkShape
      
      print(<Input the Dataframe name which you want the output of>.shape())
      

      【讨论】:

      • 这正是@Louis Yang 3 年前写的内容
      猜你喜欢
      • 1970-01-01
      • 2015-07-05
      • 1970-01-01
      • 1970-01-01
      • 2018-05-12
      • 2020-10-06
      • 1970-01-01
      • 2021-03-25
      相关资源
      最近更新 更多