我有以下适用于 pandas 数据框的函数
def event_list(df,steps):
df['steps_present'] = df['labels'].apply(lambda x:all(step in x for step in steps))
return df
DataFrame 有一个名为 labels 的列,其值为列表。此函数接受数据帧和步骤(这是一个列表),并输出带有新列步骤的数据帧,如果参数列表中的所有元素都存在于数据帧列中
value in df['labels'] = [EBBY , ABBY , JULIE , ROBERTS]
event_list(df,['EBBY','ABBY'])
将为该记录返回 True,因为 EBBY 和 ABBY 出现在数据帧列表列中。
我想在 pyspark 中创建类似的函数。
最佳答案
您可以使用array_except
来检查所提供列表中的每个元素是否都出现在标签列中。如果是,则 array_except
结果的大小将为 0。将大小与 0 进行比较将得到您想要的 bool 值。
import pyspark.sql.functions as F
def event_list(df, steps):
return df.withColumn(
'steps_present',
F.size(F.array_except(F.array(*[F.lit(l) for l in steps]), 'labels')) == 0
)
df2 = event_list(df, ["EBBY", "ABBY"])
df2.show(truncate=False)
+----------------------------+-------------+
|labels |steps_present|
+----------------------------+-------------+
|[EBBY, ABBY, JULIE, ROBERTS]|true |
|[EBBY, JULIE] |false |
+----------------------------+-------------+
关于python - 检查给定列表中的元素是否存在于 DataFrame 的数组列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66912148/