开发者社区> 问答> 正文

加入两个列表列值,如Pyspark中的zip

我有一个pandas数据帧。我试图首先将包含字符串值的两列连接到列表中,然后使用zip,我使用'_'连接列表的每个元素。我的数据集如下:

df['column_1']: 'abc, def, ghi'
df['column_2']: '1.0, 2.0, 3.0'
我想在我的数据帧的每一行的第三列中加入这两列,如下所示。

df['column_3']: [abc_1.0, def_2.0, ghi_3.0]
我已经使用下面的代码在python中成功完成了,但是数据帧非常大,并且需要很长时间才能为整个数据帧运行它。我想在Pyspark做同样的事情以提高效率。我已成功读取spark数据帧中的数据,但我很难确定如何使用pyspark等效函数复制pandas函数。如何在pyspark获得我想要的结果?

df['column_3'] = df['column_2']
for index, row in df.iterrows():
while index < 3:

if isinstance(row['column_1'], str):      
  row['column_1'] = list(row['column_1'].split(','))
  row['column_2'] = list(row['column_2'].split(','))
  row['column_3'] = ['_'.join(map(str, i)) for i in zip(list(row['column_1']), list(row['column_2']))]

我已经使用下面的代码将两列转换为Pyspark中的数组

from pyspark.sql.types import ArrayType, IntegerType, StringType
from pyspark.sql.functions import col, split

crash.withColumn("column_1",

split(col("column_1"), ",\s*").cast(ArrayType(StringType())).alias("column_1")

)
crash.withColumn("column_2",

split(col("column_2"), ",\s*").cast(ArrayType(StringType())).alias("column_2")

)
现在我需要的是使用'_'压缩两列中数组的每个元素。我怎么能用这个zip?

展开
收起
一码平川MACHEL 2019-01-22 10:43:17 2844 0
1 条回答
写回答
取消 提交回答
  • 您还可以使用UDF压缩拆分数组列,

    df = spark.createDataFrame([('abc,def,ghi','1.0,2.0,3.0')], ['col1','col2'])
    col1col2
    abc,def,ghi1.0,2.0,3.0

    +-----------+-----------+ ## Hope this is how your dataframe is

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

    def concat_udf(*args):

    return ['_'.join(x) for x in zip(*args)]
    

    udf1 = F.udf(concat_udf,ArrayType(StringType()))
    df = df.withColumn('col3',udf1(F.split(df.col1,','),F.split(df.col2,',')))

    df.show(1,False)
    col1col2col3
    abc,def,ghi1.0,2.0,3.0[abc_1.0, def_2.0, ghi_3.0]
    2019-07-17 23:26:09
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Data Wrangling with PySpark fo 立即下载
Spark + Parquet in Depth 立即下载
LEARNINGS USING SPARK STREAMING & DATAFRAMES FOR WALMART SEARCH 立即下载