考虑以下数据帧
cols = ['Id', 'col1', 'col2', 'col3']
vals = [('1A','Not his side|:|This side', 'This side', 'Not this either|:|but this'),
('1B','Keep this', 'This one|:|keep this', 'remove|:|keep that')]
dd1 = sqlContext.createDataFrame(vals, cols)
#+---+------------------------+--------------------+--------------------------+
#|Id |col1 |col2 |col3 |
#+---+------------------------+--------------------+--------------------------+
#|1A |Not his side|:|This side|This side |Not this either|:|but this|
#|1B |Keep this |This one|:|keep this|remove|:|keep that |
#+---+------------------------+--------------------+--------------------------+
我需要做的是在|:|
处拆分字符串并保留第二个单词。但是,如果字符串不包含分隔符(|:|
),则得到null
,
i、 电子邮件:
users1 = [F.split(F.col(x), "\\|:\\|").alias(x) for x in cols]
dd1.select(*users1).show()
#+---------+---------+---------+
#| col1| col2| col3|
#+---------+---------+---------+
#|This side| null| but this|
#| null|keep this|keep that|
#+---------+---------+---------+
我想要的结果是:
+---+---------+---------+---------+
|Id |col1 |col2 |col3 |
+---+---------+---------+---------+
|1A |This side|This side|but this |
|1B |Keep this|keep this|keep that|
+---+---------+---------+---------+
可以使用
when
和size
内置函数作为这应该给你
您可以修改答案,以便只使用
split
函数一次。你知道吗我希望答案是有益的,应该是一个很好的提示如何进行。你知道吗
使用
when
和otherwise
并检查字符串是否包含"|:|"
。具体做法如下:这里的
cols
只包含要拆分的列。最后的select
也将包含Id
列。你知道吗您在问题中定义的选择不会产生您提到的结果。我想你忘了从数组中选择元素;)
要实现所需的功能,只需选择数组的最后一个元素。您可以使用size函数:
相关问题 更多 >
编程相关推荐