PySpark:如何判断数据框中列的类型

10
假设我们有一个名为df的数据框。我知道可以使用df.dtypes的方式。不过我更喜欢类似于下面这样的方式: type(123) == int # 注意这里的int不是字符串 我想知道是否有像这样的方式: type(df.select(<column_name>).collect()[0][1]) == IntegerType 基本上,我想直接从数据框中获取类似于IntegerType、StringType等的对象,然后进行判断。
谢谢!
3个回答

14

TL;DR 使用外部数据类型(纯 Python 类型)来测试值,使用内部数据类型(DataType 子类)来测试模式。


首要的是 - 您不应该使用

type(123) == int

正确检查 Python 中类型的方法(处理继承)是:

isinstance(123, int)

完成此操作后,让我们来谈谈

基本上我想知道如何直接从数据帧中获取类似于IntegerType、StringType的对象,然后进行判断。

这不是它的工作方式。 DataTypes 描述的是模式(内部表示),而不是值。外部类型是一个普通的 Python 对象,因此如果内部类型是 IntegerType,则外部类型是 int 等等,根据在 Spark SQL 编程指南 中定义的规则。

唯一存在 IntegerType(或其他 DataTypes)实例的地方是您的模式:

from pyspark.sql.types import *

df = spark.createDataFrame([(1, "foo")])

isinstance(df.schema["_1"].dataType, LongType)
# True
isinstance(df.schema["_2"].dataType, StringType)
# True

_1, _2 = df.first()

isinstance(_1, int)
# True
isinstance(_2, str)
# True

2
尝试以下内容怎么样:

如何尝试:

df.printSchema()

这将返回类似以下内容的结果:
root
 |-- id: integer (nullable = true)
 |-- col1: string (nullable = true)
 |-- col2: string (nullable = true)
 |-- col3: integer (nullable = true)
 |-- col4: date (nullable = true)
 |-- col5: long (nullable = true)

1
如果需要在ArrayType或StructType模式下检查详细结构,我更喜欢使用df.dtypes,然后使用类型对象中的XXXType.simpleString()更轻松地验证复杂模式。例如,
import pyspark.sql.types as T

df_dtypes = dict(df.dtypes)
# {'column1': 'array<string>',
#  'column2': 'array<struct<fieldA:string,fieldB:bigint>>'}


### if want to verify the complex type schema
column1_require_type = T.ArrayType(T.StringType())
column2_require_type = T.ArrayType(T.StructType([
    T.StructField("fieldA", T.StringType()),
    T.StructField("fieldB", T.LongType()),
]))

column1_type_string = column1_require_type.simpleString() # array<string>
column2_type_string = column2_require_type.simpleString() # array<struct<fieldA:string,fieldB:bigint>>

# easy verification for complex structure
assert df_dtypes['column1'] == column1_type_string  # True
assert df_dtypes['column2'] == column2_type_string  # True

我认为如果需要验证复杂模式,这很有帮助。这对我有用(我正在使用PySpark 3.2)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接