【问题标题】:Validating the data type of a column in pyspark dataframe验证pyspark数据框中列的数据类型
【发布时间】:2018-02-19 02:05:07
【问题描述】:

我有 3 列的 pyspark 数据框。 配置单元表“test1”的 DDL 都具有字符串数据类型。 所以如果我做 df.printSchema 都是字符串数据类型,如下图,

>>> df = spark.sql("select * from default.test1")
>>> df.printSchema()                                                                                                                                                                     
root                                                                                                                                                                                       
 |-- c1: string (nullable = true)                                                                                                                                            
 |-- c2: string (nullable = true)                                                                                                                                        
 |-- c3: string (nullable = true)  

+----------+--------------+-------------------+                                                                                                                 
|c1        |c2            |c3                 |                                                                                                                 
+----------+--------------+-------------------+                                                                                                                 
|April     |20132014      |4                  |                                                                                                                 
|May       |20132014      |5                  |                                                                                                                 
|June      |abcdefgh      |6                  |                                                                                                                 
+----------+--------------+-------------------+ 

现在我只想过滤“c2”列中的整数类型的记录。 所以基本上我只需要前 2 个整数类型的记录,如“20132014”。并排除其他记录。

【问题讨论】:

    标签: python apache-spark pyspark apache-spark-sql


    【解决方案1】:

    一行:

    df.withColumn("c2", df["c2"].cast("integer")).na.drop(subset=["c2"])
    

    如果c2 不是有效整数,则它将为NULL 并在后续步骤中删除。

    不改变类型

    valid = df.where(df["c2"].cast("integer").isNotNull())
    invalid = df.where(df["c2"].cast("integer").isNull())
    

    【讨论】:

      猜你喜欢
      • 2019-01-23
      • 2018-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-02
      • 2021-09-06
      • 1970-01-01
      相关资源
      最近更新 更多