我试图找出 PySpark 中 DataFrame 的大小/形状。我没有看到可以做到这一点的单一功能。
在 Python 中,我可以这样做:
data.shape()
PySpark 中是否有类似的功能?这是我目前的解决方案,但我正在寻找一个元素
row_number = data.count()
column_number = len(data.dtypes)
列数的计算并不理想...
data.shape
? shape
不是函数。
您可以通过以下方式获取其 shape
:
print((df.count(), len(df.columns)))
使用 df.count()
获取行数。
将此添加到您的代码中:
import pyspark
def spark_shape(self):
return (self.count(), len(self.columns))
pyspark.sql.dataframe.DataFrame.shape = spark_shape
然后你可以做
>>> df.shape()
(10000, 10)
但请提醒您,对于尚未持久化的非常大的表,.count()
可能会非常慢。
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)
我认为 Spark 中没有类似 data.shape
的功能。但我会使用 len(data.columns)
而不是 len(data.dtypes)
我已经使用这个代码块解决了这个问题。请尝试一下,它有效。
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())
不定期副业成功案例分享
.shape
那样简单地存储形状值?对于这样一个常见且简单的操作,必须调用 count 似乎非常耗费资源。