PySpark:如何用逗号将列指定为小数

cph*_*sto 8 csv format comma pyspark

我正在使用 PySpark 并加载csv文件。我有一列带有欧洲格式的数字,这意味着逗号替换了点,反之亦然。

例如:我有2.416,67而不是2,416.67.

My data in .csv file looks like this -    
ID;    Revenue
21;    2.645,45
23;   31.147,05
.
.
55;    1.009,11
Run Code Online (Sandbox Code Playgroud)

在 Pandas 中,通过在内部指定decimal=','thousands='.'选项pd.read_csv()来读取欧洲格式,可以轻松读取这样的文件。

熊猫代码:

import pandas as pd
df=pd.read_csv("filepath/revenues.csv",sep=';',decimal=',',thousands='.')
Run Code Online (Sandbox Code Playgroud)

我不知道如何在 PySpark 中做到这一点。

PySpark 代码:

from pyspark.sql.types import StructType, StructField, FloatType, StringType
schema = StructType([
            StructField("ID", StringType(), True),
            StructField("Revenue", FloatType(), True)
                    ])
df=spark.read.csv("filepath/revenues.csv",sep=';',encoding='UTF-8', schema=schema, header=True)
Run Code Online (Sandbox Code Playgroud)

谁能建议我们如何使用上述.csv()函数在 PySpark 中加载这样的文件?

jho*_*e89 5

You won't be able to read it as a float because the format of the data. You need to read it as a string, clean it up and then cast to float:

from pyspark.sql.functions import regexp_replace
from pyspark.sql.types import FloatType

df = spark.read.option("headers", "true").option("inferSchema", "true").csv("my_csv.csv", sep=";")
df = df.withColumn('revenue', regexp_replace('revenue', '\\.', ''))
df = df.withColumn('revenue', regexp_replace('revenue', ',', '.'))
df = df.withColumn('revenue', df['revenue'].cast("float"))
Run Code Online (Sandbox Code Playgroud)

You can probably just chain these all together too:

df = spark.read.option("headers", "true").option("inferSchema", "true").csv("my_csv.csv", sep=";")
df = (
         df
         .withColumn('revenue', regexp_replace('revenue', '\\.', ''))
         .withColumn('revenue', regexp_replace('revenue', ',', '.'))
         .withColumn('revenue', df['revenue'].cast("float"))
     )
Run Code Online (Sandbox Code Playgroud)

Please note this I haven't tested this so there may be a typo or two in there.

  • 嗨 jhole89,只需替换 '.' 和 '\\。' 在第一个正则表达式中,因为 DOT 匹配正则表达式中的所有内容,并将 FloatType 更改为“float”以使此代码工作。除此之外,代码完美运行。 (2认同)