如何删除 Pyspark 数据框中的 utf 格式并将列从字符串转换为整数

How to remove utf format in a dataframe in Pyspark and convert column from string to Integer

我需要删除 utf 格式并将列转换为整数类型。

以下是我删除 utf 格式所做的工作

>>auction_data = auction_raw_data.map(lambda line: line.encode("ascii","ignore").split(","))
>>auction_Data.take(2)
>>[['8211480551', '52.99', '1.201505', 'hanna1104', '94', '49.99', '311.6'], ['8211480551', '50.99', '1.203843', 'wrufai1', '90', '49.99', '311.6']]

但是,当我使用模式为相同数据创建数据框并尝试检索特定数据时,我得到的数据以“u”为前缀。

>>schema = StructType([ StructField("auctionid", StringType(), True),
StructField("bid", StringType(), True),
StructField("bidtime", StringType(), True),
StructField("bidder", StringType(), True),
StructField("bidderrate", StringType(), True),
StructField("openbid", StringType(), True),
StructField("price", StringType(), True)])`  

>>xbox_df = sqlContext.createDataFrame(auction_data,schema)
>>xbox_df.registerTempTable("auction")
>>first_line = sqlContext.sql("select * from auction where auctionid=8211480551").collect()
>>for i in first_line:
>>   print i

>>Row(auctionid=u'8211480551', bid=u'52.99', bidtime=u'1.201505', bidder=u'hanna1104', bidderrate=u'94', openbid=u'49.99', price=u'311.6')
>>Row(auctionid=u'8211480551', bid=u'50.99', bidtime=u'1.203843', bidder=u'wrufai1', bidderrate=u'90', openbid=u'49.99', price=u'311.6')

如何删除值前面的 u',我还想将出价转换为整数。当我直接更改模式定义时,我收到一条错误消息 “ TypeError: IntegerType 不能接受类型中的对象”。少显示

我正在加载 JSON 而不是使用模式,所以我不知道是否有区别。使用 select 时将字段转换为 int 没有问题。这就是我所做的:

from pyspark.sql.functions import *
...
df = df.select(col('intField').cast('int'))
df.show()
# prints Row(intField=123)