仅从 pyspark 中的 Spark DF 选择数字/字符串列名称

新手上路,请多包涵

我在 Pyspark (2.1.0) 中有一个 Spark DataFrame,我希望仅获取数字列的名称或仅获取字符串列的名称。

例如,这是我的 DF 的架构:

 root
 |-- Gender: string (nullable = true)
 |-- SeniorCitizen: string (nullable = true)
 |-- MonthlyCharges: double (nullable = true)
 |-- TotalCharges: double (nullable = true)
 |-- Churn: string (nullable = true)

这就是我需要的:

 num_cols = [MonthlyCharges, TotalCharges]
str_cols = [Gender, SeniorCitizen, Churn]

我怎样才能做到?

原文由 Mara 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 633
2 个回答

dtypes 是元组列表 (columnNane,type) 你可以使用简单的过滤器

 columnList = [item[0] for item in df.dtypes if item[1].startswith('string')]

原文由 zlidime 发布,翻译遵循 CC BY-SA 3.0 许可协议

PySpark 提供了丰富的与模式 类型 相关的 API。正如@DanieldePaula 提到的,您可以通过 df.schema.fields 访问字段的元数据。

这是一种基于静态类型检查的不同方法:

 from pyspark.sql.types import StringType, DoubleType

df = spark.createDataFrame([
  [1, 2.3, "t1"],
  [2, 5.3, "t2"],
  [3, 2.1, "t3"],
  [4, 1.5, "t4"]
], ["cola", "colb", "colc"])

# get string
str_cols = [f.name for f in df.schema.fields if isinstance(f.dataType, StringType)]
# ['colc']

# or double
dbl_cols = [f.name for f in df.schema.fields if isinstance(f.dataType, DoubleType)]
# ['colb']

原文由 abiratsis 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题