combining multiple rows in Spark dataframe column based on condition

允我心安 提交于 2019-12-11 03:06:49

问题


I am trying to combine multiple rows in a spark dataframe based on a condition:

This is the dataframe I have(df):

|username | qid | row_no | text  |
 ---------------------------------
|  a      | 1   |  1     | this  |
|  a      | 1   |  2     |  is   |
|  d      | 2   |  1     |  the  |
|  a      | 1   |  3     | text  |
|  d      | 2   |  2     |  ball |

I want it to look like this

|username | qid | row_no | text        |
 ---------------------------------------
|   a     | 1   |  1,2,3 | This is text|
|   b     | 2   |  1,2   | The ball    |

I am using spark 1.5.2 it does not have collect_list function


回答1:


collect_list showed up only in 1.6.

I'd go through the underlying RDD. Here's how:

data_df.show()
+--------+---+------+----+
|username|qid|row_no|text|
+--------+---+------+----+
|       d|  2|     2|ball|
|       a|  1|     1|this|
|       a|  1|     3|text|
|       a|  1|     2|  is|
|       d|  2|     1| the|
+--------+---+------+----+

Then this

reduced = data_df\
    .rdd\
    .map(lambda row: ((row[0], row[1]), [(row[2], row[3])]))\
    .reduceByKey(lambda x,y: x+y)\
    .map(lambda row: (row[0], sorted(row[1], key=lambda text: text[0]))) \
    .map(lambda row: (
            row[0][0], 
            row[0][1], 
            ','.join([str(e[0]) for e in row[1]]),
            ' '.join([str(e[1]) for e in row[1]])
        )
    )

schema_red = typ.StructType([
        typ.StructField('username', typ.StringType(), False),
        typ.StructField('qid', typ.IntegerType(), False),
        typ.StructField('row_no', typ.StringType(), False),
        typ.StructField('text', typ.StringType(), False)
    ])

df_red = sqlContext.createDataFrame(reduced, schema_red)
df_red.show()

The above produced the following:

+--------+---+------+------------+
|username|qid|row_no|        text|
+--------+---+------+------------+
|       d|  2|   1,2|    the ball|
|       a|  1| 1,2,3|this is text|
+--------+---+------+------------+

In pandas

df4 = pd.DataFrame([
        ['a', 1, 1, 'this'],
        ['a', 1, 2, 'is'],
        ['d', 2, 1, 'the'],
        ['a', 1, 3, 'text'],
        ['d', 2, 2, 'ball']        
    ], columns=['username', 'qid', 'row_no', 'text'])

df_groupped=df4.sort_values(by=['qid', 'row_no']).groupby(['username', 'qid'])

df3 = pd.DataFrame()
df3['row_no'] = df_groupped.apply(lambda row: ','.join([str(e) for e in row['row_no']]))
df3['text']   = df_groupped.apply(lambda row: ' '.join(row['text']))

df3 = df3.reset_index()



回答2:


You can apply groupBy on username and qid column then follow by agg() method you can use collect_list() method like this

import pyspark.sql.functions as func

then you will have collect_list()or some other important functions

for detail abput groupBy and agg you can follow this URL.

Hope this solves your problem

Thanks



来源:https://stackoverflow.com/questions/43356725/combining-multiple-rows-in-spark-dataframe-column-based-on-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!