
[英]How can I assign a variable from column 2 when running a loop of values in column 1 (same ROW value)
[英]How can I parse a row's column value passed to a UDF when mapping a column?
我有一个像这样的 dataframe,为了简单起见,我只显示 2 列,两列都是string
,但在现实生活中,除了string
之外,它还有更多不同类型的列:
SQL文本 | 表名 |
---|---|
select * 来自源表; | 新表 |
select * 来自 sourceTable1; | 新表1 |
我还有一个自定义 Function,我想在其中迭代 dataframe 并获取sql
并运行它来创建一个表,但是我没有单独传递每一列,而是传递整行:
def CreateTables(rowp):
df = spark.sql(rowp.SQLText)
#code to create table using rowp.TableName
这是我的代码,我首先清理SQLText
,因为它存储在另一个表中,然后我在该列上运行 UDF:
l = l.withColumn("SQLText", F.lit(F.regexp_replace(F.col("SQLText").cast("string"), "[\n\r]", " ")))
nt = l.select(l["*"]).withColumn("TableName",CreateTables(F.struct(*list(l.columns)) )).select("TableName","SQLText")
nt.show(truncate=False)
因此,当我运行 function 并尝试运行上面的代码时,它出错了,因为它没有将rowp.SQLText
解析为其文字值,而是传递了它的类型?:
Column<'struct(SourceSQL, TableName)[SourceSQL]'>
因此,在CreateTables
function 中,当执行spark.sql(rowp.SQLText)
时,我预计会出现以下情况:
df = spark.sql("select * from sourceTable;")
但这正在发生,实际上是发送变量类型而不是变量值
df = spark.sql("Column<'struct(SourceSQL, TableName)[SourceSQL]'>")
我尝试了很多解决方案: getItem
、 getField
、 get
、 getAs
但还没有成功。
我也试过使用像rowp[0]
这样的索引,但它只是改变了传递给spark.sql
function 的变量类型:
Column<'struct(SourceSQL, TableName)[0]'>
如果我尝试rowp(0)
它会给我一个Column is not callable
错误。
有很多方法可以做到这一点。
这是我在 pyspark 3.2.3 中测试的一种方法
rows = df.rdd.collect()
for i in range(len(rows)):
spark.sql(rows[i][0])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.