我有以上数据框:
from pyspark.sql.types import *
rdd = sc.parallelize([
('ALT', ['chien', 'chat'] , 'oiseau'),
('ALT', ['oiseau'] , 'oiseau'),
('TDR', ['poule','poulet'], 'poule' ),
('ALT', ['ours'] , 'chien' ),
('ALT', ['paon'] , 'tigre' ),
('TDR', ['tigre','lion'] , 'lion' ),
('ALT', ['chat'] ,'chien' ),
])
schema = StructType([StructField("ClientId",StringType(),True),
StructField("Animaux",ArrayType(StringType(),True),True),
StructField("Animal",StringType(),True),])
test = rdd.toDF(schema)
test.show()
+--------+---------------+------+
|ClientId| Animaux|Animal|
+--------+---------------+------+
| ALT| [chien, chat]|oiseau|
| ALT| [oiseau]|oiseau|
| TDR|[poule, poulet]| poule|
| ALT| [ours]| chien|
| ALT| [paon]| tigre|
| TDR| [tigre, lion]| lion|
| ALT| [chat]| chien|
+--------+---------------+------+
我想创建一个新的列,它将取值" 1"如果列中的字符串" Animal"列在#34; Animaux"列中和" 0"否则。
我试过了:
test2=test.withColumn("isinlist", F.when("Animal in Animaux", 'ok').otherwise('pas ok'))
test2=test.withColumn("isinlist", F.when(test.Animal.isin(*test.Animaux), 'ok').otherwise('pas ok'))
test.where("Animal in (Animaux)").show()
test.where("Animal in Animaux").show()
test2=test.withColumn("isinlist", F.when(test.Animal.isin(test.Animaux), 'ok').otherwise('pas ok'))
但它都不起作用...... 有没有人知道怎么做而不使用udf ...有直接的方法吗?
答案 0 :(得分:5)
您可以使用array_contains
:
from pyspark.sql.functions import expr
test.withColumn("isinlist", expr("array_contains(Animaux, Animal)")).show()
# +--------+---------------+------+--------+
# |ClientId| Animaux|Animal|isinlist|
# +--------+---------------+------+--------+
# | ALT| [chien, chat]|oiseau| false|
# | ALT| [oiseau]|oiseau| true|
# | TDR|[poule, poulet]| poule| true|
# | ALT| [ours]| chien| false|
# | ALT| [paon]| tigre| false|
# | TDR| [tigre, lion]| lion| true|
# | ALT| [chat]| chien| false|
# +--------+---------------+------+--------+
来自How to filter Spark dataframe if one column is a member of another column(Scala)的来源zero323。