【问题标题】:PySpark UDF returns a string but I need an integerPySpark UDF 返回一个字符串,但我需要一个整数
【发布时间】:2020-11-02 02:39:32
【问题描述】:

我有这段代码,我从 UDF 返回一个整数类型,但系统将其更改为字符串。

我该如何纠正这个问题?

# Define a UDF to determine the number of pixels per image
def dogPixelCount(doglist):
totalpixels = 0
for dog in doglist:
    totalpixels += (dog[3] - dog[1]) * (dog[4] - dog[2])
return totalpixels

# Define a UDF for the pixel count
udfDogPixelCount = F.udf(dogPixelCount, IntegerType())
joined_df = joined_df.withColumn('dog_pixels', udfDogPixelCount('dogs'))

# Create a column representing the percentage of pixels
joined_df = joined_df.withColumn('dog_percent', ('dog_pixels' / sum('dog_pixels') ) * 100 )

# Show the first 10 annotations with more than 60% dog
joined_df.filter(dog_percent > 60).show(10)

【问题讨论】:

  • 在这里发帖时请不要大喊大叫。全部大写的文本更难阅读和理解,并且不会帮助您更快地获得答案。当您要求我们提供免费帮助时,对我们大喊大叫也是相当不礼貌的。谢谢。

标签: dataframe pyspark user-defined-functions


【解决方案1】:

在 Python 中,只需使用简单的语法 x = int(String),例如:

num = '10'
  
# check and print type num variable 
print(type(num))  
  
# convert the num into string  
converted_num = int(num) 
  
# print type of converted_num 
print(type(converted_num)) 
  
# We can check by doing some mathematical operations 
print(converted_num + 20)
result:
<class 'str'>
<class 'int'>
30

将字符串转换为整数。所以让我们把 int (YourStringNeededToConvert) 改成整数。

【讨论】:

    【解决方案2】:

    如果没有完整的上下文,您似乎需要使用来自pyspark.sql.functionscol/sum函数,而不是列名的字符串 (dog_pixels) 和内置的sum 函数。试试这个:

    import pyspark.sql.functions as F
    ...
    
    joined_df = joined_df.withColumn('dog_percent', (F.col('dog_pixels') / F.sum('dog_pixels') ) * 100 )
    

    【讨论】:

      猜你喜欢
      • 2018-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-20
      • 2012-09-20
      • 1970-01-01
      • 2019-02-26
      相关资源
      最近更新 更多