2017-04-10 45 views
0

我一直在试图替换特定列的数据集中的字符串。如果是1或0,则为'Y',否则为0.pyspark sql函数而不是rdd不同

我已经成功地确定了要使用lambda进行数据框到rdd转换的目标列,但需要一段时间才能处理。

切换到每个列的rdd然后执行一个独特的,这是需要一段时间!

如果在不同的结果集中存在'Y',则该列被标识为需要转换。

我想知道是否有人可以建议我如何可以专门使用pyspark sql函数来获得相同的结果,而不必切换每列?

代码,样本数据,如下:

import pyspark.sql.types as typ 
    import pyspark.sql.functions as func 

    col_names = [ 
     ('ALIVE', typ.StringType()), 
     ('AGE', typ.IntegerType()), 
     ('CAGE', typ.IntegerType()), 
     ('CNT1', typ.IntegerType()), 
     ('CNT2', typ.IntegerType()), 
     ('CNT3', typ.IntegerType()), 
     ('HE', typ.IntegerType()), 
     ('WE', typ.IntegerType()), 
     ('WG', typ.IntegerType()), 
     ('DBP', typ.StringType()), 
     ('DBG', typ.StringType()), 
     ('HT1', typ.StringType()), 
     ('HT2', typ.StringType()), 
     ('PREV', typ.StringType()) 
     ] 

    schema = typ.StructType([typ.StructField(c[0], c[1], False) for c in col_names]) 
    df = spark.createDataFrame([('Y',22,56,4,3,65,180,198,18,'N','Y','N','N','N'), 
           ('N',38,79,3,4,63,155,167,12,'N','N','N','Y','N'), 
           ('Y',39,81,6,6,60,128,152,24,'N','N','N','N','Y')] 
           ,schema=schema) 

    cols = [(col.name, col.dataType) for col in df.schema] 

    transform_cols = [] 

    for s in cols: 
     if s[1] == typ.StringType(): 
     distinct_result = df.select(s[0]).distinct().rdd.map(lambda row: row[0]).collect() 
     if 'Y' in distinct_result: 
      transform_cols.append(s[0]) 

    print(transform_cols) 

输出是:

['ALIVE', 'DBG', 'HT2', 'PREV'] 

回答

1

我设法为了做任务用udf。首先,选择与YN列(在这里我以通过第一行脱脂使用func.first):

cols_sel = df.select([func.first(col).alias(col) for col in df.columns]).collect()[0].asDict() 
cols = [col_name for (col_name, v) in cols_sel.items() if v in ['Y', 'N']] 
# return ['HT2', 'ALIVE', 'DBP', 'HT1', 'PREV', 'DBG'] 

接下来,你可以以图YN10创建udf功能。

def map_input(val): 
    map_dict = dict(zip(['Y', 'N'], [1, 0])) 
    return map_dict.get(val) 
udf_map_input = func.udf(map_input, returnType=typ.IntegerType()) 

for col in cols: 
    df = df.withColumn(col, udf_map_input(col)) 
df.show() 

最后,您可以对列进行求和。然后我变换输出到词典,并检查哪些列具有大于0的值(即,包含Y

out = df.select([func.sum(col).alias(col) for col in cols]).collect() 
out = out[0] 
print([col_name for (col_name, val) in out.asDict().items() if val > 0]) 

输出

['DBG', 'HT2', 'ALIVE', 'PREV'] 
+1

感谢,它不一定是更有效的,但它是有用看到另一个解决方案,因为我是pyspark的新手。 – alortimor

+0

欢迎您!我希望这会有所帮助! – titipata