上下文: 我需要使用isin函数基于包含另一个数据框的列的内容过滤数据框。
对于使用熊猫的Python用户,应该为:isin()。
对于R用户,应为:%in%。
所以我有一个带有id和value列的简单spark数据框:
l = [(1, 12), (1, 44), (1, 3), (2, 54), (3, 18), (3, 11), (4, 13), (5, 78)]
df = spark.createDataFrame(l, ['id', 'value'])
df.show()
+---+-----+
| id|value|
+---+-----+
| 1| 12|
| 1| 44|
| 1| 3|
| 2| 54|
| 3| 18|
| 3| 11|
| 4| 13|
| 5| 78|
+---+-----+
Run Code Online (Sandbox Code Playgroud)
我想获取所有出现多次的ID。这是df中唯一ID的数据框:
unique_ids = df.groupBy('id').count().where(col('count') < 2)
unique_ids.show()
+---+-----+
| id|count| …Run Code Online (Sandbox Code Playgroud) 在对数据集应用 RandomForestClassifier 进行二元分类和预测后,我获得了一个带有标签、预测和概率列的转换数据帧df。
目标:
我想创建一个新列“prob_flag”,它是预测标签“1”的概率。它是包含概率的数组的第二个元素(本身是第一个数组的第三个元素)。
我查看了类似的主题,但出现了这些主题中未遇到的错误。
df.show()
label prediction probability
0 0 [1,2,[],[0.7558548984793847,0.2441451015206153]]
0 0 [1,2,[],[0.5190322149055472,0.4809677850944528]]
0 1 [1,2,[],[0.4884140358521083,0.5115859641478916]]
0 1 [1,2,[],[0.4884140358521083,0.5115859641478916]]
1 1 [1,2,[],[0.40305518381637956,0.5969448161836204]]
1 1 [1,2,[],[0.40570407426458577,0.5942959257354141]]
# The probability column is VectorUDT and looks like an array of dim 4 that contains probabilities of predicted variables I want to retrieve
df.schema
StructType(List(StructField(label,DoubleType,true),StructField(prediction,DoubleType,false),StructField(probability,VectorUDT,true)))
# I tried this:
import pyspark.sql.functions as f
df.withColumn("prob_flag", f.array([f.col("probability")[3][1])).show()
"Can't extract value from probability#6225: need struct type but …Run Code Online (Sandbox Code Playgroud)