使用pyspark洗牌随机选择的列
我试图做到:使用pyspark洗牌随机选择的列,pyspark,Pyspark,我试图做到: 从数据框中随机选择几列 从“从步骤1中选择”列中洗牌该值 将步骤2中的这些列添加回数据帧 代码如下: # Step 0: create data frame using list and tuple df = sqlContext.createDataFrame([ ("user1", 0, 1, 0, 1, 0, 1, 1, 0, 1, 0), ("user2", 1, 1, 0, 1, 0, 1, 1, 1, 1, 0), ("u
# Step 0: create data frame using list and tuple
df = sqlContext.createDataFrame([
("user1", 0, 1, 0, 1, 0, 1, 1, 0, 1, 0),
("user2", 1, 1, 0, 1, 0, 1, 1, 1, 1, 0),
("user3", 1, 1, 1, 1, 0, 0, 0, 1, 1, 0),
("user4", 0, 1, 0, 1, 1, 1, 1, 1, 0, 0),
("user5", 1, 1, 1, 1, 0, 1, 0, 1, 1, 0),
("user6", 0, 1, 0, 1, 1, 1, 1, 0, 1, 0)
], ["ID", "x0", "x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9"])
df.show()
数据帧是:
第一步很有效。随机选择的特征为“x0”、“x4”
# shuffle the random selected columns to create random noise feature
for i in range(0, 2):
# Step 2: shuffle the value from the column select from step 1
rnd_df = df.select(random_col[i]).orderBy(F.rand(i)).withColumnRenamed(random_col[i], 'rnd_col').rnd_col
# step 3: add these columns from step 2 back to the DataFrame
df = df.withColumn('random'+ str(i+1), rnd_df)
第二步很有效。但步骤3失败,出现以下错误。有人知道如何解决这个问题吗?
除非执行联接,否则无法将外部列添加到它不属于的数据帧中。我想是这样的。但是,如何通过对现有列中的一列进行无序排列来添加列呢?实际上,该列是从原始表中派生出来的,您可以为每一行(1到N)创建一个id。你洗牌你的新列,然后为每一行(1到N)添加一个id,并在该id上进行连接…你不能将外部列添加到它不属于的数据帧,除非你执行连接。我想是这样的。但是,如何通过对现有列中的一列进行无序排列来添加列呢?实际上,该列是从原始表中派生出来的,您可以为每一行(1到N)创建一个id。您洗牌您的新列,然后为每一行(1到N)添加一个id并加入该id。。。
# shuffle the random selected columns to create random noise feature
for i in range(0, 2):
# Step 2: shuffle the value from the column select from step 1
rnd_df = df.select(random_col[i]).orderBy(F.rand(i)).withColumnRenamed(random_col[i], 'rnd_col').rnd_col
# step 3: add these columns from step 2 back to the DataFrame
df = df.withColumn('random'+ str(i+1), rnd_df)