来自RDD和DataFrame的不同浮点精度

时间:2018-01-26 16:04:43

标签: apache-spark pyspark spark-dataframe rdd

我将RDD更改为DataFrame并将结果与​​我使用read.csv导入的另一个DataFrame进行比较,但浮点精度与两种方法不同。感谢您的帮助。

我使用的数据来自here

x

RDD方式

from pyspark.sql import Row
from pyspark.sql.types import *

数据帧

orders = sc.textFile("retail_db/orders")
order_items = sc.textFile('retail_db/order_items')
orders_comp = orders.filter(lambda line: ((line.split(',')[-1] == 'CLOSED') or  (line.split(',')[-1] == 'COMPLETE')))
orders_compMap = orders_comp.map(lambda line: (int(line.split(',')[0]), line.split(',')[1]))

order_itemsMap = order_items.map(lambda line: (int(line.split(',')[1]), 
                                           (int(line.split(',')[2]), float(line.split(',')[4])) ))

 joined = orders_compMap.join(order_itemsMap)
 joined2 = joined.map(lambda line: ((line[1][0], line[1][1][0]), line[1][1][1]))

joined3 = joined2.reduceByKey(lambda a, b : a +b).sortByKey()

df1 = joined3.map(lambda x:Row(date = x[0][0], product_id = x[0][1], total  = x[1])).toDF().select(['date','product_id', 'total'])

它们是一样的吗?

 schema = StructType([StructField('order_id', IntegerType(), True),
                StructField('date', StringType(), True),
                StructField('customer_id', StringType(), True),
                 StructField('status', StringType(), True)])


 orders2 = spark.read.csv("retail_db/orders",schema = schema)


 schema = StructType([StructField('item_id', IntegerType(), True),
                StructField('order_id', IntegerType(), True),
                StructField('product_id', IntegerType(), True),
                 StructField('quantity', StringType(), True),
                 StructField('sub_total', FloatType(), True),
                 StructField('product_price', FloatType(), True)])



orders_items2 = spark.read.csv("retail_db/order_items", schema = schema)

orders2.registerTempTable("orders2t")
orders_items2.registerTempTable("orders_items2t")

 df2 = spark.sql('select o.date, oi.product_id, sum(oi.sub_total)  \
      as total from  orders2t as o inner join orders_items2t as oi on 
      o.order_id = oi.order_id \
      where o.status in ("CLOSED", "COMPLETE") group by o.date, 
     oi.product_id order by  o.date, oi.product_id')

enter image description here

1 个答案:

答案 0 :(得分:1)

忽略转换中的精度损失并不相同。

使用DoubleType可能更接近:

  

DoubleType:表示8字节的双精度浮点数。

但如果可预测的行为很重要,则应使用具有明确定义精度的DecimalTypes