get(#)
或getAs [Type] (#)
从数据框中获取值。在pyspark
中应该如何实现?
我有一个包含两列的DataFrame:item(字符串)
和salesNum(整数)
。 我进行了groupby
和mean
操作以获取这些数字的平均值,如下所示:
saleDF.groupBy("salesNum").mean()).collect()
它能够正常工作。 现在我获得了一个包含一个值的数据框来表示平均值。
怎样从数据框中获得该值以获取平均值的浮点数呢?get(#)
或getAs [Type] (#)
从数据框中获取值。在pyspark
中应该如何实现?
我有一个包含两列的DataFrame:item(字符串)
和salesNum(整数)
。 我进行了groupby
和mean
操作以获取这些数字的平均值,如下所示:
saleDF.groupBy("salesNum").mean()).collect()
它能够正常工作。 现在我获得了一个包含一个值的数据框来表示平均值。
怎样从数据框中获得该值以获取平均值的浮点数呢?collect()
将结果以 Python 列表的形式返回。要从列表中获取值,只需要像这样取第一个元素:
saleDF.groupBy("salesNum").mean()).collect()[0]
准确地说,collect
返回的是一个列表,其元素的类型为class 'pyspark.sql.types.Row'
。
在您的情况下,如果要提取真实值,应该执行以下操作:
saleDF.groupBy("salesNum").mean()).collect()[0]["avg(yourColumnName)"]
yourColumnName
是您要求平均值的列的名称(使用mean函数时,pyspark默认以此方式重命名结果列)。
例如,我运行了以下代码。查看每个步骤的类型和输出。
>>> columns = ['id', 'dogs', 'cats', 'nation']
>>> vals = [
... (2, 0, 1, 'italy'),
... (1, 2, 0, 'italy'),
... (3, 4, 0, 'france')
... ]
>>> df = sqlContext.createDataFrame(vals, columns)
>>> df.groupBy("nation").mean("dogs").collect()
[Row(nation=u'france', avg(dogs)=4.0), Row(nation=u'italy', avg(dogs)=1.0)]
>>> df.groupBy("nation").mean("dogs").collect()[0]
Row(nation=u'france', avg(dogs)=4.0))
>>> df.groupBy("nation").mean("dogs").collect()[0]["avg(dogs)"]
4.0
>>> type(df.groupBy("nation").mean("dogs").collect())
<type 'list'>
>>> type(df.groupBy("nation").mean("dogs").collect()[0])
<class 'pyspark.sql.types.Row'>
>>> type(df.groupBy("nation").mean("dogs").collect()[0]["avg(dogs)"])
<type 'float'>
>>>
>>>
在这里,我们也可以使用first()
。
saleDF.groupBy("salesNum").mean()).first()[0]