我的木星笔记本里有火花数据框。我想对列“关键字”中的特定值进行排序。我只需要返回那些有一个或几个匹配值的行。
下面是我需要排序的列的样子。
+--------------------+
| Keywords|
+--------------------+
| ["apocalypse"]|
|["nuclear","physi...|
| null|
|["childhood","imm...|
|["canned tomatoes...|
| null|
|["american","beef...|
|["runway","ethose...|
|["taylor swift st...|
|["beauty","colleg...|
| null|
|["curly hair|coil...|
|["glossier|shoppi...|
|["stacey abrams",...|
|["quentin taranti...|
| null|
|["Mexican|Cinco D...|
|["Bridal Spring 2...|
| null|
|["everyday athlet...|
+--------------------+
我想要创建一个新的数据,只有当关键字=“美”,“跑道”行。我该怎么做?我本来打算用Python创建一个for循环,但不知道如何在中实现.任何帮助都将不胜感激。
发布于 2019-12-04 13:59:10
对于一般的解决方案,可以使用列表指定要包含的单词/关键字作为输出的一部分,并在df
的筛选器中使用。
代码看起来如下:
from pyspark.sql.functions import udf
from pyspark.sql.types import BooleanType
valid_words = {"beauty", "runway"} # Define a list of valid words
filtered_df = df.filter(udf(lambda kwords: len(valid_words & set(kwords))>0, # Condition to identify if we have at least, 1 valid word
BooleanType())(df.Keywords))
filtered_df.show()
因此,如果需要包含任何其他有效单词,则只需更新列表(valid_words
)。
此外,标题应该更新,这与排序无关,更多的是对给定ArrayType列的行进行过滤。
发布于 2019-12-04 12:36:15
Since the expected output is difficult to define, this can be used for what I have understood so far.
from pyspark.sql.types import *
from pyspark.sql import SparkSession
import pyspark.sql.functions as F
from pyspark.sql.functions import udf
spark = SparkSession.builder.appName('test').getOrCreate()
df = spark.createDataFrame([[["apocalypse"]],[[None]],[["beauty","test"]],[["runway","beauty"]]]).toDF("testcol")
df.show()
+----------------+
| testcol|
+----------------+
| [apocalypse]|
| []|
| [beauty, test]|
|[runway, beauty]|
+----------------+
df.filter(F.array_contains(F.col("testcol"),"beauty")|F.array_contains(F.col("testcol"),"runway")).show()
+----------------+
| testcol|
+----------------+
| [beauty, test]|
|[runway, beauty]|
+----------------+
https://stackoverflow.com/questions/59184203
复制