python - 展开 PySpark DataFrame 的数组列

标签 python dataframe pyspark graphframes

我必须使用下面的数据将 DataFrame 传输到 GraphFrame 中。让我们考虑数据框中的一列作者,其中包含如下所示的字符串数组:

+-----------+------------------------------------+
|ArticlePMID|               Authors              |
+-----------+------------------------------------+
|    PMID1  |['Author 1', 'Author 2', 'Author 3']|
|    PMID2  |['Author 4', 'Author 5']            |
+-----------+------------------------------------+

在数据表中,我们有共同合作完成同一篇论文的作者列表。现在我想将第二列扩展为包含以下结构的新数据框:

+---------------+---------------+ 
| Collaborator1 | Collaborator2 |
+---------------+---------------+ 
| 'Author 1'    | 'Author 2'    |
| 'Author 1'    | 'Author 3'    |
| 'Author 2'    | 'Author 3'    |
| 'Author 4'    | 'Author 5'    |
+---------------+---------------+

我尝试使用爆炸函数,但这只会将数组扩展为单列作者,并且我失去了协作网络。

有人可以告诉我如何解决这个问题吗?

最佳答案

只要您使用 pyspark 2.1 或更高版本,就可以使用 posexplode随后是加入:

首先用数组中的位置进行爆炸:

from pyspark.sql.functions import posexplode
exploded = df.select("*", posexplode("Authors").alias("pos", "Author"))
exploded.show()
#+-----------+--------------------+---+--------+
#|ArticlePMID|             Authors|pos|  Author|
#+-----------+--------------------+---+--------+
#|      PMID1|[Author 1, Author...|  0|Author 1|
#|      PMID1|[Author 1, Author...|  1|Author 2|
#|      PMID1|[Author 1, Author...|  2|Author 3|
#|      PMID2|[Author 4, Author 5]|  0|Author 4|
#|      PMID2|[Author 4, Author 5]|  1|Author 5|
#+-----------+--------------------+---+--------+

现在,在 ArticlePMID 列上将分解的 DataFrame 连接到自身,并仅选择左侧表的 pos 小于右侧表的列。

exploded.alias("l").join(exploded.alias("r"), on="ArticlePMID", how="inner")\
    .where("l.pos < r.pos")\
    .selectExpr("l.Author AS Collaborator1", "r.Author AS Collaborator2")\
    .show()
#+-------------+-------------+
#|Collaborator1|Collaborator2|
#+-------------+-------------+
#|     Author 1|     Author 2|
#|     Author 1|     Author 3|
#|     Author 2|     Author 3|
#|     Author 4|     Author 5|
#+-------------+-------------+

使用pos进行过滤是为了避免同一对作者同时列出。

关于python - 展开 PySpark DataFrame 的数组列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56185672/

相关文章:

python - ValueError : Expected 2D array, 在拟合模型时得到一维数组

python - 如何在 PySpark 中删除 RDD 以释放资源?

python - Pandas - 将字符串更改为数字

python - 将浮点值舍入到区间限制/网格

python - python扭曲静态文件中的变量替换

r - 过滤R中包含字符和数字的特定范围值中的行

javascript - 将数据帧与 OpenCPU 的 JavaScript 库一起使用

python - 使用 Spark 并行运行不同的分类器/算法

python - 我应该将广播变量或broadcast.value()传递到我的RDD[自定义对象]中吗?

python - 如何在 PySpark 中创建空的 Spark DataFrame 并追加数据?