PySpark DataFrame Floor division unsupported operand type(s)

Viewed 6069

I have a dataset like below:

enter image description here

I am group by age and average on numbers of friends for each age

from pyspark.sql import SparkSession
from pyspark.sql import Row
import pyspark.sql.functions as F

def parseInput(line):
    fields = line.split(',')
    return Row(age = int(fields[2]), numFriends = int(fields[3]))

spark = SparkSession.builder.appName("FriendsByAge").getOrCreate()
lines = spark.sparkContext.textFile("data/fakefriends.csv")
friends = lines.map(parseInput)
friendDataset = spark.createDataFrame(friends)
counts = friendDataset.groupBy("age").count()
total = friendDataset.groupBy("age").sum('numFriends')
res = total.join(counts, "age").withColumn("Friend By Age", (F.col("sum(numFriends)") // F.col("count"))).drop('sum(numFriends)','count')

I got below error:

TypeError: unsupported operand type(s) for //: 'Column' and 'Column'

Usually, I use // in Python 3.0+ and return an integer value as I expected here, however, in PySpark datagram, // doesn't work and only / works. Any reason why it doesn't work? We have to use round function to get integer value?

2 Answers

Not sure about the reason. but you can type cast to int or use Floor function

from pyspark.sql import functions as F
tst= sqlContext.createDataFrame([(1,7,9),(1,8,4),(1,5,10),(5,1,90),(7,6,18),(0,3,11)],schema=['col1','col2','col3'])
tst1 = tst.withColumn("div", (F.col('col1')/F.col('col2')).cast('int'))
tst2 = tst.withColumn("div", F.floor(F.col('col1')/F.col('col2')))

//(floor division) is not supported in pyspark over column. Try below alternative-

counts = friendDataset.groupBy("age").count()
total = friendDataset.groupBy("age").agg(sum('numFriends').alias('sum'))
res = total.join(counts, "age").withColumn("Friend By Age", F.floor(F.col("sum") / F.col("count"))).drop('sum(numFriends)','count')

Related