明白了,为什么这种方式无法正常工作。首先,您尝试从行类型获取整数,collect的输出如下所示:
>>> mvv_list = mvv_count_df.select('mvv').collect()
>>> mvv_list[0]
Out: Row(mvv=1)
如果您采取这样的做法:
>>> firstvalue = mvv_list[0].mvv
Out: 1
您将获得mvv
价值。如果您需要数组的所有信息,则可以采取以下方法:
>>> mvv_array = [int(row.mvv) for row in mvv_list.collect()]
>>> mvv_array
Out: [1,2,3,4]
但是,如果对另一列尝试相同的操作,则会得到:
>>> mvv_count = [int(row.count) for row in mvv_list.collect()]
Out: TypeError: int() argument must be a string or a number, not 'builtin_function_or_method'
发生这种情况是因为它count
是一种内置方法。并且该列的名称与相同count
。一种解决方法是将列名称更改count
为_count
:
>>> mvv_list = mvv_list.selectExpr("mvv as mvv", "count as _count")
>>> mvv_count = [int(row._count) for row in mvv_list.collect()]
但是不需要此解决方法,因为您可以使用字典语法访问列:
>>> mvv_array = [int(row['mvv']) for row in mvv_list.collect()]
>>> mvv_count = [int(row['count']) for row in mvv_list.collect()]
它将最终成功!
list(df.select('mvv').toPandas()['mvv'])
。 Arrow已集成到PySpark中,从而toPandas
大大加快了速度。如果您使用的是Spark 2.3+,请不要使用其他方法。请参阅我的答案以获取更多基准测试详细信息。