【问题标题】:Slit column into multiple columns using pyspark 2.4 [duplicate]使用pyspark 2.4将列分成多列[重复]
【发布时间】:2019-07-15 09:50:08
【问题描述】:

我们如何使用 pyspark2.4 根据像“/”这样的分隔符拆分 sparkDataframe 列

我的专栏包含:

+-------------------+
|           timezone|
+-------------------+
|   America/New_York|
|  Africa/Casablanca|
|      Europe/Madrid|
|      Europe/Madrid|
|                   |
|   Null            |

谢谢

【问题讨论】:

  • 你期望什么输出?如果存在分隔符,有两个单独的列?

标签: python pyspark


【解决方案1】:
# Creating a dataframe
values = [('America/New_York',),('Africa/Casablanca',),('Europe/Madrid',),('Europe/Madrid',),('Germany',),('',),(None,)]
df = sqlContext.createDataFrame(values,['timezone',])
df.show(truncate=False)
+-----------------+
|timezone         |
+-----------------+
|America/New_York |
|Africa/Casablanca|
|Europe/Madrid    |
|Europe/Madrid    |
|Germany          |
|                 |
|null             |
+-----------------+

from pyspark.sql.functions import instr, split
df = df.withColumn('separator_if_exists',(instr(col('timezone'),'/') > 0) & instr(col('timezone'),'/').isNotNull())
df = df.withColumn('col1',when(col('separator_if_exists') == True,split(col('timezone'),'/')[0]).otherwise(None))
df = df.withColumn('col2',when(col('separator_if_exists') == True,split(col('timezone'),'/')[1]).otherwise(None)).drop('separator_if_exists')
df.show(truncate=False)

+-----------------+-------+----------+
|timezone         |col1   |col2      |
+-----------------+-------+----------+
|America/New_York |America|New_York  |
|Africa/Casablanca|Africa |Casablanca|
|Europe/Madrid    |Europe |Madrid    |
|Europe/Madrid    |Europe |Madrid    |
|Germany          |null   |null      |
|                 |null   |null      |
|null             |null   |null      |
+-----------------+-------+----------+

文档: split()instr()。请注意,instr() 是基于 1 的索引。如果没有找到要查找的子串,则返回0。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-24
    • 2013-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多