我是Pypark的新手。 我尝试使用包含自定义项的配置文件提取数据帧的列。 如果我在客户机上将select列定义为一个列表,那么它可以工作,但是如果我从配置文件导入列表,那么列列表的类型是string。 有别的办法吗。你知道吗
使用pyspark打开火花壳。你知道吗
*******************************************************************
version 2.2.0
Using Python version 2.7.16 (default, Mar 18 2019 18:38:44)
SparkSession available as 'spark'
*******************************************************************
jsonDF = spark.read.json("/tmp/people.json")
jsonDF.show()
+----+-------+
| age| name|
+----+-------+
|null|Michael|
| 30| Andy|
| 19| Justin|
+----+-------+
jsonDF.printSchema()
root
|-- age: long (nullable = true)
|-- name: string (nullable = true)
jsonCurDF = jsonDF.filter(jsonDF.age.isNotNull()).cache()
# Define the UDF
from pyspark.sql.functions import udf
@udf("long")
def squared_udf(s):
return s * s
# Selecting the columns from a list.
colSelList = ['age', 'name', squared_udf('age')]
jsonCurDF.select(colSelList).show()
+---+------+----------------+
|age| name|squared_udf(age)|
+---+------+----------------+
| 30| Andy| 900|
| 19|Justin| 361|
+---+------+----------------+
# If I use an external config file
colSelListStr = ["age", "name" , "squared_udf('age')"]
jsonCurDF.select(colSelListStr).show()
上面的命令失败“cannot resolve'`squared\u udf('age')”
尝试注册函数,尝试selectExpr并使用column函数。你知道吗
在colSelList中,udf调用被转换为列类型。你知道吗
print colSelList[2]
Column<squared_udf(age)
print colSelListStr[2]
squared_udf('age')
print column(colSelListStr[2])
Column<squared_udf('age')
我做错什么了?或者有别的解决办法吗?你知道吗
这是因为当你从列表中传递它时,平方年龄被认为是字符串而不是函数。 有一个圆的方法,你可以这样做,你不需要为此导入自定义项。 假设这是您需要选择的列表
直接传递此列表将导致错误,因为此数据帧中不包含平方年龄
因此,首先将现有df的所有列按
这些就是你需要的专栏![enter image description here](https://i.stack.imgur.com/WeSpu.png)
现在把这两个列表交起来 它会给你一个常用元素列表
现在试试这个
给你这个
希望这有帮助。你知道吗
相关问题 更多 >
编程相关推荐