python-3.x - PySpark:如何为所有列转换字符串数据类型
问题描述
我的主要目标是将任何 df 的所有列转换为字符串,这样比较就很容易了。
我已经尝试了以下多种已经建议的方法。但无法成功:
target_df = target_df.select([col(c).cast("string") for c in target_df.columns])
这给出了错误:
pyspark.sql.utils.AnalysisException: "Can't extract value from SDV#155: need struct type but got string;"
我尝试过的下一个是:
target_df = target_df.select([col(c).cast(StringType()).alias(c) for c in columns_list])
错误 :
pyspark.sql.utils.AnalysisException: "Can't extract value from SDV#27: need struct type but got string;"
下一个方法是:
for column in target_df.columns:
target_df = target_df.withColumn(column, target_df[column].cast('string'))
错误 :
pyspark.sql.utils.AnalysisException: "Can't extract value from SDV#27: need struct type but got string;"
cast 之前存在的几行代码:
columns_list = source_df.columns.copy()
target_df = target_df.toDF(*columns_list)
我正在尝试的示例 df 的架构:
root
|-- A: string (nullable = true)
|-- S: string (nullable = true)
|-- D: string (nullable = true)
|-- F: string (nullable = true)
|-- G: double (nullable = true)
|-- H: double (nullable = true)
|-- J: string (nullable = true)
|-- K: string (nullable = true)
|-- L: string (nullable = true)
|-- M: string (nullable = true)
|-- N: string (nullable = true)
|-- B: string (nullable = true)
|-- V: string (nullable = true)
|-- C: string (nullable = true)
|-- X: string (nullable = true)
|-- Y: string (nullable = true)
|-- U: double (nullable = true)
|-- I: string (nullable = true)
|-- R: string (nullable = true)
|-- T: string (nullable = true)
|-- Q: string (nullable = true)
|-- E: double (nullable = true)
|-- W: string (nullable = true)
|-- AS: string (nullable = true)
|-- DSC: string (nullable = true)
|-- DCV: string (nullable = true)
|-- WV: string (nullable = true)
|-- SDV: string (nullable = true)
|-- SDV.1: string (nullable = true)
|-- WDV: string (nullable = true)
|-- FWFV: string (nullable = true)
|-- ERBVSER: string (nullable = true)
解决方案
如建议的那样,错误来自.
命名列中的点,SDV.1
在选择列时必须用反引号括起来:
for column in target_df.columns:
target_df = target_df.withColumn(column, target_df['`{}`'.format(column)].cast('string'))
或者
target_df = target_df.select([col('`{}`'.format(c)).cast(StringType()).alias(c) for c in columns_list])
推荐阅读
- php - Laravel 7 奇怪的注销问题
- python - 使用另一个按钮覆盖 kivy 中的按钮功能
- mysql - Node 和 MYSQL 中的“连接太多”错误
- java - Java:在线程内运行时 JNDI 查找失败
- swift - 无法检查查询结果是否为零
- angular - 将primeng toast放在角度6的共享组件上时,第一次单击时未打开
- php - Base64解码在php中没有给出值
- python - Visual Studio 2015中python字符串的f格式
- arduino - 连续两次调用analogWrite 后,Arduino Mega2560 重新启动
- linux - Anaconda Navigator 无法在 Linux Mint 上启动