Skip to main content
 首页 » 编程设计

python之验证 pyspark 数据框中列的数据类型

2024年10月01日27lyj

我有 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”。并排除其他记录。

请您参考如下方法:

一行:

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