【问题标题】:Reshaping RDD from an array of array to unique columns in pySpark将RDD从数组数组重塑为pySpark中的唯一列
【发布时间】:2018-09-26 10:22:29
【问题描述】:

我想使用pySpark 来重组我的数据,以便我可以将它用于MLLib 模型,目前对于每个用户,我在一列中有一个数组数组,我想将其转换为具有计数的唯一列.

Users | column1                  |
user1 | [[name1, 4], [name2, 5]] |
user2 | [[name1, 2], [name3, 1]] |

应该转换为:

Users | name1   | name2   | name3   |
user1 | 4.0     | 5.0     | 0.0     |
user2 | 2.0     | 0.0     | 1.0     |

我想出了一种使用 for 循环的方法,但我正在寻找一种可以利用 spark 的方法,因为数据量很大。你能给我一些提示吗?谢谢。

编辑: 所有唯一名称都应作为单独的列出现,并带有对应于每个用户的分数。基本上,一个稀疏矩阵。 我现在正在使用 pandas,我用来执行此操作的代码是

data = data.applymap(lambda x: dict(x))    # To convert the array of array into a dictionary
columns = list(data)
for i in columns:
    # For each columns using the dictionary to make a new Series and appending it to the current dataframe
    data = pd.concat([data.drop([i], axis=1), data[i].apply(pd.Series)], axis=1)    

【问题讨论】:

  • 欢迎来到 SO。你能更详细地描述你的问题吗?例如。通过添加描述您的问题的代码、命令或屏幕截图。另请查看帮助中心,尤其是askingminimal examples。谢谢。
  • @CKE,感谢您的回复。抱歉,这是我第一次发帖提问。现在看起来还可以吗?
  • 是的,确实如此。感谢您的编辑。
  • 您是否知道将预先创建的列名称,或者它会根据数据而变化。示例:name1name2name3 等等。
  • 可能因数据而异

标签: pyspark rdd transformation


【解决方案1】:

想出了答案,

import pyspark.sql.functions as F
# First we explode column`, this makes each element as a separate row
df= df.withColumn('column1', F.explode_outer(F.col('column1')))
# Then, seperate out the new column1 into two columns
df = df.withColumn(("column1_seperated"), F.col('column1')[0])
df= df.withColumn("count", F.col(i)['column1'].cast(IntegerType()))
# Then pivot the df
df= df.groupby('Users').pivot("column1_seperated").sum('count')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-13
    • 1970-01-01
    • 1970-01-01
    • 2017-01-03
    • 1970-01-01
    相关资源
    最近更新 更多