我有以下内容PySpark 输入数据框:
+-------+------------+
| index | valuelist |
+-------+------------+
| 1.0 | [10,20,30] |
| 2.0 | [11,21,31] |
| 0.0 | [14,12,15] |
+-------+------------+
Where:
- 索引:双精度型
- 值列表:类型Vector. (it's 非数组)
从上面的输入数据框中,我想得到以下内容输出数据帧 in PySpark
+-------+-------+
| index | value |
+-------+-------+
| 1.0 | 20 |
| 2.0 | 31 |
| 0.0 | 14 |
+-------+-------+
Logic:
for each row:
value = valuelist[index]
Spark 1.5 及更高版本
您可以使用pyspark.sql.functions.expr
to 将列值作为输入传递给函数 https://stackoverflow.com/questions/51140470/using-a-column-value-as-a-parameter-to-a-spark-dataframe-function:
df.select("index", f.expr("valuelist[CAST(index AS integer)]").alias("value")).show()
#+-----+-----+
#|index|value|
#+-----+-----+
#| 1.0| 20|
#| 2.0| 31|
#| 0.0| 14|
#+-----+-----+
Spark 2.1 及更高版本
如果你有spark
版本 2.1 或更高版本,这里有一个替代方法pyspark.sql.functions.posexplode
:
import pyspark.sql.functions as f
df.select("index", f.posexplode("valuelist").alias("pos", "value"))\
.where(f.col("index").cast("int") == f.col("pos"))\
.select("index", "value")\
.show()
#+-----+-----+
#|index|value|
#+-----+-----+
#| 1.0| 20|
#| 2.0| 31|
#| 0.0| 14|
#+-----+-----+
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)