【问题标题】:PySpark: How to drop non-numeric columnsfr a DataFrame?PySpark:如何删除 DataFrame 中的非数字列?
【发布时间】:2020-03-11 21:16:52
【问题描述】:

我想从 DataFrame 中删除所有非数字的列。我正在尝试复制一些这样做的 Pandas 代码:

df = df[df.select_dtypes(exclude=['object']).columns]

我将如何为 PySpark DataFrame 执行此操作?

【问题讨论】:

    标签: python pyspark


    【解决方案1】:

    首先,请找到here 不同 PySpark 类型的参考。

    下面的代码删除了字符串 cols:

    df = spark.createDataFrame([
        (1, "a", "xxx", None, "abc", "xyz","fgh"), 
        (2, "b", None, 3, "abc", "xyz","fgh"),
        (3, "c", "a23", None, None, "xyz","fgh")
    ], ("ID","flag", "col1", "col2", "col3", "col4", "col5"))
    
    from pyspark.sql.types import *
    num_cols = [f.name for f in df.schema.fields if not isinstance(f.dataType, StringType)]
    
    df2 = df.select([c for c in num_cols])
    df2.show()
    
    +---+----+
    | ID|col2|
    +---+----+
    |  1|null|
    |  2|   3|
    |  3|null|
    +---+----+
    

    或者(准确地说)您可以将not isinstance 替换为isinstance,并包含您感兴趣的上述链接中的类型。 希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2012-09-25
      • 2017-05-28
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      • 2023-03-16
      • 2018-12-21
      • 2020-05-14
      相关资源
      最近更新 更多