Bakground
我们正在将数据从Redshift卸载到S3中,然后将其加载到数据帧中,如下所示:
df = spark.read.csv(path, schema=schema, sep='|')
我们正在使用PySpark和AWS EMR(版本5.4.0)与Spark 2.1.0。
问题
我有一个Redshift表,正在以CSV格式读入PySpark。记录采用以下格式:
url,category1,category2,category3,category4
http://example.com,0.6,0.0,0.9,0.3
url 是VARCHAR,类别值是FLOAT介于0.0和1.0之间。
我想要做的是生成一个新的DataFrame,每个类别有一行,其中原始数据集中的值高于某个阈值X.例如,如果阈值设置为0.5,那么我希望我的新数据集看起来像这样:
url,category
http://example.com,category1
http://example.com,category3
我是Spark / PySpark的新手,所以我不确定如何做到这一点是否可行,我们将不胜感激!
编辑:
想要添加我的解决方案(基于Pushkr的代码)。我们有一个TON类别要加载,以避免硬编码每个选择我做了以下:
parsed_df = None
for column in column_list:
if not parsed_df:
parsed_df = df.select(df.url, when(df[column]>threshold,column).otherwise('').alias('cat'))
else:
parsed_df = parsed_df.union(df.select(df.url, when(df[column]>threshold,column).otherwise('')))
if parsed_df is not None:
parsed_df = parsed_df.filter(col('cat') != '')
其中 column_list 是以前生成的类别列名称列表, threshold 是选择类别所需的最小值。
再次感谢!
答案 0 :(得分:1)
这是我尝试过的东西 -
UserRole::create()
输出:
data = [('http://example.com',0.6,0.0,0.9,0.3),('http://example1.com',0.6,0.0,0.9,0.3)]
df = spark.createDataFrame(data)\
.toDF('url','category1','category2','category3','category4')
from pyspark.sql.functions import *
df\
.select(df.url,when(df.category1>0.5,'category1').otherwise('').alias('category'))\
.union(\
df.select(df.url,when(df.category2>0.5,'category2').otherwise('')))\
.union(\
df.select(df.url,when(df.category3>0.5,'category3').otherwise('')))\
.union(\
df.select(df.url,when(df.category4>0.5,'category4').otherwise('')))\
.filter(col('category')!= '')\
.show()