将句子的数据帧“规范化”为更大的单词数据帧

2024-04-29 02:58:48 发布

您现在位置:Python中文网/ 问答频道 /正文

使用Python和Spark:

假设我有一个数据帧,其中的行包含句子,那么如何将句子数据帧(来自DBMS terms)转换成另一个数据帧,其中每行包含一个从句子中分离出来的单词?在

我想这主要是telegraph problem。在

例如,假设df_sentences如下所示:

[Row(sentence_id=1, sentence=u'the dog ran the fastest.'),
 Row(sentence_id=2, sentence=u'the cat sat down.')]

我在寻找df_sentencesdf_words的转换,它将使用这两行并构建一个更大(行计数)的数据帧,如下所示。请注意,句子“_id”被带到新表中:

^{pr2}$

现在,我对行数或唯一字不感兴趣,这是因为我想连接到sentence_id上的其他RDD,以获取存储在其他地方的其他有趣的数据。在

我怀疑spark中的很多功能都是围绕着管道中的这些间歇转换的,所以我想了解做事情的最佳方法,并开始收集我自己的代码片段


Tags: the数据iddfsentences单词telegraphsentence
1条回答
网友
1楼 · 发布于 2024-04-29 02:58:48

其实很简单。让我们从创建DataFrame开始:

from pyspark.sql import Row

df = sc.parallelize([
    Row(sentence_id=1, sentence=u'the dog ran the fastest.'),
     Row(sentence_id=2, sentence=u'the cat sat down.')
]).toDF()

接下来我们需要一个标记器:

^{pr2}$

最后我们删除sentence和{}words

from pyspark.sql.functions import explode, col

transformed = (tokenized
    .drop("sentence")
    .select(col("sentence_id"), explode(col("words")).alias("word")))

最终结果是:

transformed.show()

## +     -+   -+
## |sentence_id|   word|
## +     -+   -+
## |          1|    the|
## |          1|    dog|
## |          1|    ran|
## |          1|    the|
## |          1|fastest|
## |          2|    the|
## |          2|    cat|
## |          2|    sat|
## |          2|   down|
## +     -+   -+

注意事项

  • 根据数据,explode可能相当昂贵,因为它复制其他列。在应用explode之前,请确保应用所有的过滤器,例如使用StopWordsRemover

相关问题 更多 >