代码之家  ›  专栏  ›  技术社区  ›  cph_sto

PySpark:如何指定逗号为十进制的列

  •  2
  • cph_sto  · 技术社区  · 8 年前

    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
    

    decimal=',' 和 thousands='.' 内部选项 pd.read_csv() 阅读欧洲格式。

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

    我不知道怎么能在Pypark做到这一点。

    Pypark代码:

    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)
    

    有人能建议我们如何使用上述方法在PySpark中加载这样的文件吗 .csv() 功能?

    2 回复  |  直到 8 年前
        1
  •  5
  •   jhole89    7 年前

    您将无法将其作为浮点读取,因为数据的格式不正确。您需要将其读取为字符串,将其清理干净,然后将其转换为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"))
    

    你也可以把它们连在一起:

    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"))
         )
    

    请注意,我还没有测试过,所以可能有一两个输入错误。

        2
  •  -1
  •   braga461    7 年前

    确保您的SQL表已预先格式化为读取数字而不是整数。 我在试图弄清楚编码以及点和逗号等的不同格式时遇到了很大的困难。最后问题变得更原始了,它被预先格式化为只读取整数,因此小数永远不会被接受,不管是逗号还是点。然后我不得不改变我的SQL表,改为接受实数(数字),就是这样。

    推荐文章