如何在Spark中关闭舍入?

2024-05-23 20:04:52 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,我有一个数据帧,我正在这样做:

df = dataframe.withColumn("test", lit(0.4219759403))

我只想得到点后的前四个数字,不需要四舍五入

当我强制转换为DecimalType时,使用.cast(DataTypes.createDecimalType(20,4) 或者,即使使用round函数,该数字也被舍入为0.4220

我发现在不进行舍入的情况下执行此操作的唯一方法是应用函数format_number(),但此函数给我一个字符串,当我将此string to DecimalType(20,4)强制转换时,框架会将数字再次舍入到0.4220

我需要在不舍入的情况下将这个数字转换为enter code here十进制(20,4),我希望看到0.4219

我该怎么做


Tags: 数据方法函数testdataframedf情况数字
2条回答

您好,欢迎来到stackoverflow,
请下次尝试使用您尝试过的代码提供一个可复制的示例,无论如何,这对我来说是有效的:

from pyspark.sql.types import DecimalType
df = spark.createDataFrame([
    (1, "a"),
    (2, "b"),
    (3, "c"),
], ["ID", "Text"])

df = df.withColumn("test", lit(0.4219759403))
df = df.withColumn("test_string", F.substring(df["test"].cast("string"), 0, 6))
df = df.withColumn("test_string_decimaltype", df["test_string"].cast(DecimalType(20,4)))
df.show()
df.printSchema()

+ -+  +      +     -+           -+
| ID|Text|        test|test_string|test_string_decimaltype|
+ -+  +      +     -+           -+
|  1|   a|0.4219759403|     0.4219|                 0.4219|
|  2|   b|0.4219759403|     0.4219|                 0.4219|
|  3|   c|0.4219759403|     0.4219|                 0.4219|
+ -+  +      +     -+           -+

root
 |  ID: long (nullable = true)
 |  Text: string (nullable = true)
 |  test: double (nullable = false)
 |  test_string: string (nullable = false)
 |  test_string_decimaltype: decimal(20,4) (nullable = true) 

当然,如果您想覆盖同一列,可以通过始终放置“test”,我选择不同的名称让您查看步骤

如果小数点前有超过1位的数字,则substr不适用。相反,您可以使用正则表达式始终提取前4位小数(如果存在)。
您可以使用^{}完成此操作

df = dataframe.withColumn('rounded', F.regexp_extract(F.col('test'), '\d+\.\d{0,4}', 0))

范例

import pyspark.sql.functions as F

dataframe = spark.createDataFrame([
    (0.4219759403, ),
    (0.4, ),
    (1.0, ),
    (0.5431293, ),
    (123.769859, )
], ['test'])
df = dataframe.withColumn('rounded', F.regexp_extract(F.col('test'), '\d+\.\d{0,4}', 0))
df.show()

+      +    +
|        test| rounded|
+      +    +
|0.4219759403|  0.4219|
|         0.4|     0.4|
|         1.0|     1.0|
|   0.5431293|  0.5431|
|  123.769859|123.7698|
+      +    +

相关问题 更多 >