将函数应用于 Spark 中 csv 的单列 [英] Apply a function to a single column of a csv in Spark
问题描述
我正在使用 Spark 读取 csv 并希望将函数应用于 csv 上的列.我有一些有效的代码,但它非常笨拙.这样做的正确方法是什么?
Using Spark I'm reading a csv and want to apply a function to a column on the csv. I have some code that works but it's very hacky. What is the proper way to do this?
我的代码
SparkContext().addPyFile("myfile.py")
spark = SparkSession\
.builder\
.appName("myApp")\
.getOrCreate()
from myfile import myFunction
df = spark.read.csv(sys.argv[1], header=True,
mode="DROPMALFORMED",)
a = df.rdd.map(lambda line: Row(id=line[0], user_id=line[1], message_id=line[2], message=myFunction(line[3]))).toDF()
我希望能够只在列名上调用函数,而不是将每一行映射到 line
,然后在 line[index]
上调用函数.
I would like to be able to just call the function on the column name instead of mapping each row to line
and then calling the function on line[index]
.
我使用的是 Spark 2.0.1 版
I'm using Spark version 2.0.1
推荐答案
您可以简单地将用户定义函数 (udf
) 与 withColumn
结合使用:
You can simply use User Defined Functions (udf
) combined with a withColumn
:
from pyspark.sql.types import IntegerType
from pyspark.sql.functions import udf
udf_myFunction = udf(myFunction, IntegerType()) # if the function returns an int
df = df.withColumn("message", udf_myFunction("_3")) #"_3" being the column name of the column you want to consider
这将向包含 myFunction(line[3])
的结果的数据框 df
添加一个新列.
This will add a new column to the dataframe df
containing the result of myFunction(line[3])
.
这篇关于将函数应用于 Spark 中 csv 的单列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!