python - pyspark - select() 函数忽略 if 语句

标签 python azure pyspark azure-databricks azure-storage-account

感谢用户@DerekO,his以下示例仅正确获取 varchar 列的最大长度。但是,当我使用加载了 csv 文件的 df 的相同示例时,它会忽略 if 语句并计算所有列的最大长度(包括整数、 double 等)

问题:在不创建自定义架构的情况下,我们如何改进下面的示例 2,使其仅显示 varchar 列的最大长度

示例 1:

from pyspark.sql.functions import col, length, max
from pyspark.sql.types import StringType
    
df = spark.createDataFrame(
    [
        (1, '2', '1'),
        (1, '4', '82'),
        (1, '2', '3'),
    ],
    ['col1','col2','col3']
)

df.select([
    max(length(col(schema.name))).alias(f'{schema.name}_max_length') 
    for schema in df.schema 
    if schema.dataType == StringType()
])
    
+---------------+---------------+
|col2_max_length|col3_max_length|
+---------------+---------------+
|              1|              2|
+---------------+---------------+

示例 2:

from pyspark.sql.functions import col, length, max
from pyspark.sql.types import StringType

df = spark.read.option("delimiter", ',').option("header", 'true').option("escape", '"').option("inferSchema", 'true')\
      .csv("abfss://myContainer@myStorageAccountName" + '.dfs.core.windows.net/' + myFile_path)

df = df.select([max(length(col(schema.name))).alias(f'{schema.name}')
    for schema in df.schema 
    if schema.dataType == StringType()
])

display(df)

#The above code displays lengths of all columns even though `csv` file contains non-varchar columns, as well, as shown below:

for schema in df.schema:
  print(schema.name+" , "+str(schema.dataType))

#Output: The csv has about 80 columns. For brevity I am displaying only the few here
Field , StringType
Field2 , StringType
Field3 , StringType
Field4 , IntegerType
Field5 , DoubleType
Field6 , LongType
Field7, StringType
Field8 , StringType
Field9 , DoubleType
.....
.....

最佳答案

老实说,我现在只是猜测,但也许使用 == 不是最佳实践,我们应该使用 isinstance 代替。

df.select([
    max(length(col(schema.name))).alias(f'{schema.name}_max_length') 
    for schema in df.schema 
    if isinstance(schema.dataType, StringType)
])

关于python - pyspark - select() 函数忽略 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75525825/

相关文章:

apache-spark - 非分区 Parquet 数据的谓词下推

apache-spark - Spark 2.0如何处理列可为空性?

python - 检查多行 pandas 中标志列的有效性

python - 根本找不到 setup.py 的发行版

Python:如何遍历行 block

azure - 如何使用应用程序洞察来捕获物联网边缘设备日志?

entity-framework - 将 Entity Framework 与 SQL Azure 结合使用 - 可靠性

python - 'charmap' 编解码器无法解码位置 33222 : character maps to <undefined> 中的字节 0x8d

Azure Function 在部署后偶尔仍运行旧代码

pyspark - 如何在 GCS 中的增量表之上创建 BQ 外部表并仅显示最新快照