如何按条件将一个sparkDataframe列拆分为两列

isr3a4wc  于 2021-05-27  发布在  Spark
关注(0)|答案(1)|浏览(398)

我想替换pysparkDataframe的一列。
Dataframe:

price
   90.16|USD

我需要:

dollar_price currency
  9016          USD

Pypark代码:

new_col = F.when(F.col("price").isNull() == False, F.substring(F.col('price'), 1, F.instr(F.col('retail_value'), '|')-1)).otherwise(null)

   new_df = df.withColumn('dollar_price', new_col)

   new_col = F.when(F.col("price").isNull() == False, F.substring(F.col('price'), F.instr(F.col('retail_value'), '|')+1, 3)).otherwise(null)

   new_df_1 = new_df.withColumn('currency', new_col)

我有个错误:

TypeError: Column is not iterable

你能告诉我我错过了什么吗?
我曾尝试将一个Dataframe列的列表拆分为两个Dataframe列
但它不起作用。
谢谢

ldioqlga

ldioqlga1#

尝试 expr 当你计算价值时 instr 功能。 Example: ```
df.show()

+---------+

| price|

+---------+

|90.16|USD|

+---------+

from pyspark.sql.functions import *
from pyspark.sql.types import *

df.withColumn("dollar_price",when(col("price").isNull()==False,expr("substring(price,1,instr(price,'|')-1)")).otherwise(None)).
withColumn("currency",when(col("price").isNull()==False,expr("substring(price,instr(price,'|')+1,3)")).otherwise(None)).
show()

+---------+------------+--------+

| price|dollar_price|currency|

+---------+------------+--------+

|90.16|USD| 90.16| USD|

+---------+------------+--------+

相关问题