给定表1,其中一列为"x",类型为String.我想创建表2,其中列为"y",它是"x"中给出的日期字符串的整数表示形式.
必不可少的是将null值保留在"y"列中.
表1(数据帧df1):
+----------+
| x|
+----------+
|2015-09-12|
|2015-09-13|
| null|
| null|
+----------+
root
|-- x: string (nullable = true)
Run Code Online (Sandbox Code Playgroud)
表2(数据帧df2):
+----------+--------+
| x| y|
+----------+--------+
| null| null|
| null| null|
|2015-09-12|20150912|
|2015-09-13|20150913|
+----------+--------+
root
|-- x: string (nullable = true)
|-- y: integer (nullable = true)
Run Code Online (Sandbox Code Playgroud)
用于将列"x"中的值转换为列"y"的用户定义函数(udf)为:
val extractDateAsInt = udf[Int, String] (
(d:String) => d.substring(0, 10)
.filterNot( "-".toSet)
.toInt )
Run Code Online (Sandbox Code Playgroud)
并且工作,处理空值是不可能的.
尽管如此,我可以做类似的事情
val extractDateAsIntWithNull = udf[Int, String] (
(d:String) =>
if (d != …Run Code Online (Sandbox Code Playgroud) scala nullable user-defined-functions apache-spark apache-spark-sql
如在Web上的许多 其他位置所述,向现有DataFrame添加新列并不简单.不幸的是,拥有此功能非常重要(即使它在分布式环境中效率低下),尤其是在尝试连接两个DataFrames时unionAll.
将null列添加到a DataFrame以便于实现最优雅的解决方法是unionAll什么?
我的版本是这样的:
from pyspark.sql.types import StringType
from pyspark.sql.functions import UserDefinedFunction
to_none = UserDefinedFunction(lambda x: None, StringType())
new_df = old_df.withColumn('new_column', to_none(df_old['any_col_from_old']))
Run Code Online (Sandbox Code Playgroud) 如下面的代码所示,我正在将一个 JSON 文件读入一个数据帧,然后从该数据帧中选择一些字段到另一个字段中。
df_record = spark.read.json("path/to/file.JSON",multiLine=True)
df_basicInfo = df_record.select(col("key1").alias("ID"), \
col("key2").alias("Status"), \
col("key3.ResponseType").alias("ResponseType"), \
col("key3.someIndicator").alias("SomeIndicator") \
)
Run Code Online (Sandbox Code Playgroud)
问题是,有时,JSON 文件没有我尝试获取的某些键,例如ResponseType. 所以它最终会抛出如下错误:
org.apache.spark.sql.AnalysisException: No such struct field ResponseType
Run Code Online (Sandbox Code Playgroud)
如何在不强制使用模式的情况下解决此问题?当它不可用时,是否可以使其在该列下返回 NULL?
我如何检测 spark 数据帧是否有列确实提到了如何检测数据帧中的列是否可用。然而,这个问题是关于如何使用该功能。