我有一个PySpark DataFrame,我已经尝试了很多示例,展示了如何基于现有列的操作创建新列,但它们似乎都不起作用 .
所以我有一个问题:
1-为什么这段代码不起作用?
from pyspark import SparkContext, SparkConf
from pyspark.sql import SQLContext
import pyspark.sql.functions as F
sc = SparkContext()
sqlContext = SQLContext(sc)
a = sqlContext.createDataFrame([(5, 5, 3)], ['A', 'B', 'C'])
a.withColumn('my_sum', F.sum(a[col] for col in a.columns)).show()
我收到错误: TypeError: Column is not iterable
EDIT: Answer 1
我发现了如何使这项工作 . 我必须使用原生Python sum
函数 . a.withColumn('my_sum', F.sum(a[col] for col in a.columns)).show()
. 它有效,但我不明白为什么 .
2-如果有办法使这个总和有效, how can I write a udf function to do this (and add the result to a new column of a DataFrame)?
import numpy as np
def my_dif(row):
d = np.diff(row) # creates an array of differences element by element
return d.mean() # returns the mean of the array
我使用的是Python 3.6.1和Spark 2.1.1 .
谢谢!
2 回答
您的问题出在本部分
for col in a.columns
因为您无法迭代结果,所以您必须: