【问题标题】:select from Pyspark dataframe using variable使用变量从 Pyspark 数据帧中选择
【发布时间】:2021-09-03 19:41:56
【问题描述】:

我正在尝试使用变量(StringStartPoint)作为起始位置在列(CompleteLine)上运行子字符串函数。

我尝试了下面给出的几个选项,但两者都因不同的原因而失败。如何在选择函数中轻松使用变量。

StringStartPoint=10

df2 = df1.select(f.substring(f.col("CompleteLine"),StringStartPoint,f.col("StringLength"))).alias('MySubString')

TypeError: Column is not iterable . This is not recognizing the 3rd parameter as a value.

df2 = df1.select(f.expr("substring(col(CompleteLine),StringStartPoint,col(StringLength))").alias('MySubString')

AnalysisException: Cannot resolve StringStartPoint given input column . This is recognizing the 2nd parameter as a dataframe field.

【问题讨论】:

标签: apache-spark pyspark apache-spark-sql


【解决方案1】:

substring() 的第三个参数应该是整数类型而不是列。

将列的长度作为第三个参数的参数传递。

StringStartPoint=10

df2 = df1.select(f.substring(f.col("CompleteLine"),StringStartPoint,f.length(f.col("CompleteLine"))).alias('MySubString'))

【讨论】:

  • StringLength 是 df1 中的整数类型字段。它已经通过长度函数进行了评估。
  • 您传递的值的类型将是Column,尽管列类型是int'。您是否需要从起点到主字符串结尾的子字符串。如果是这种情况,如果你使用它,也不需要传递长度 - df.select(expr('substring(CompleteLine, 10)'))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-29
  • 2016-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多