繁体   English   中英

在数据框的新列中需要术语频率// scala

[英]need term frequency in new column of dataframe // scala

我有这个数据框:

+----------+--------+---------+-------------+----+
|article_id|     sen|    token|          ner| pos|
+----------+--------+---------+-------------+----+
|         1|example1|Standford| Organisation| NNP|
|         1|example1|       is|            O|  VP|
|         1|example1|       is|     LOCATION| ADP|
|         2|example2|Standford|Organisation2|NNP2|
|         2|example2|       is|           O2| VP2|
|         2|example2|     good|    LOCATION2|ADP2|
+----------+--------+---------+-------------+----+

我需要一个称为“ term_frequency”的新列,该列为我提供:

  • 前面的2
  • 斯坦福大学前面有1个

    因为我需要用article_id中出现它们的次数来映射它们。

我猜是这样的:

df2.withColumn("termFrequency",'token.map(s => (s,1).reduceByKey(_ + _)))或创建新的UDF。

数据框架构如下:

root
 |-- article_id: long (nullable = true)
 |-- sen: string (nullable = true)
 |-- token: string (nullable = true)
 |-- ner: string (nullable = true)
 |-- pos: string (nullable = true)

您可以在两列上按双倍分组获得结果:

>>> from pyspark.sql import Row
>>> lines = sc.textFile("data.txt")
>>> parts = lines.map(lambda l: l.split(","))
>>> articles = parts.map(lambda p: Row(article_id=int(p[0]), sen=p[1], token=p[2], ner=p[3], pos=p[4]))
>>> df = articles.toDF()

>>> df.count()
6

>>> df.groupBy("article_id", "token").count().show()
+----------+---------+-----+
|article_id|    token|count|
+----------+---------+-----+
|         1|Standford|    1|
|         1|       is|    2|
|         2|Standford|    1|
|         2|       is|    1|
|         2|     good|    1|
+----------+---------+-----+

您可以将此新表注册为一个表,将原始表注册为一个表,然后执行联接以再次获得一个表:

>>> sqlContext.registerDataFrameAsTable(df, "terms")
>>> sqlContext.registerDataFrameAsTable(freq, "freq")
>>> sqlContext.sql("SELECT * FROM terms JOIN freq ON terms.article_id = freq.article_id AND terms,token = freq.token").show()
+----------+-------------+----+--------+---------+----------+---------+-----+
|article_id|          ner| pos|     sen|    token|article_id|    token|count|
+----------+-------------+----+--------+---------+----------+---------+-----+
|         1| Organisation| NNP|example1|Standford|         1|Standford|    1|
|         1|            O|  VP|example1|       is|         1|       is|    2|
|         1|     LOCATION| ADP|example1|       is|         1|       is|    2|
|         2|Organisation2|NNP2|example2|Standford|         2|Standford|    1|
|         2|           O2| VP2|example2|       is|         2|       is|    1|
|         2|    LOCATION2|ADP2|example2|     good|         2|     good|    1|
+----------+-------------+----+--------+---------+----------+---------+-----+

希望这可以帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM