我想得到一個情緒比率,為此我需要計算每個主題有多少正面和多少負面,然后將其除以每個主題的記錄總數。
假設我有這個資料集:
----- ---------
|topic|sentiment|
----- ---------
|Chair| positive|
|Table| negative|
|Chair| negative|
|Chair| negative|
|Table| positive|
|Table| positive|
|Table| positive|
----- ---------
在這種情況下,我可以將值 -1 賦予“負”,將 1 賦予“正”,那么這個比率將0.5在 Table的情況下(negative positive positive positive) / total_count),-0.33在 Chair 的情況下:(positive negative negative) / total_count)。
我想出了這個解決方案,但似乎太復雜了:
from pyspark.sql import SparkSession
from pyspark.sql.types import StructType, StructField, StringType
from pyspark.sql.functions import col, when
spark = SparkSession.builder.appName('SparkExample').getOrCreate()
data_e = [("Chair","positive"),
("Table","negative"),
("Chair","negative"),
("Chair","negative"),
("Table","positive"),
("Table","positive")
]
schema_e = StructType([ \
StructField("topic",StringType(),True), \
StructField("sentiment",StringType(),True), \
])
df_e = spark.createDataFrame(data=data_e,schema=schema_e)
df_e_int = df_e.withColumn('sentiment_int',
when(col('sentiment') == 'positive', 1) \
.otherwise(-1)) \
.select('topic', 'sentiment_int')
agg_e = df_e_int.groupBy('topic') \
.count() \
.select('topic',
col('count').alias('counts'))
agg_sum_e = df_e_int.groupBy('topic') \
.sum('sentiment_int') \
.select('topic',
col('sum(sentiment_int)').alias('sum_value'))
agg_joined_e = agg_e.join(agg_sum_e,
agg_e.topic == agg_sum_e.topic,
'inner') \
.select(agg_e.topic, 'counts', 'sum_value')
final_agg_e = agg_joined_e.withColumn('sentiment_ratio',
(col('sum_value')/col('counts'))) \
.select('topic', 'sentiment_ratio')
最終輸出如下所示:
----- -------------------
|topic| sentiment_ratio|
----- -------------------
|Chair|-0.3333333333333333|
|Table| 0.5 |
----- -------------------
這樣做最有效的方法是什么?
uj5u.com熱心網友回復:
您可以使用avg將您的邏輯壓縮為兩行:
from pyspark.sql import functions as F
df_e.groupBy("topic") \
.agg(F.avg(F.when(F.col("sentiment").eqNullSafe("positive"), 1).otherwise(-1))) \
.show()
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/457315.html
標籤:阿帕奇火花 pyspark apache-spark-sql
上一篇:更改Pyspark中Arraytype列的任何欄位的資料型別
下一篇:為什么相等的磁區資料作業得更快?
