【发布时间】:2021-10-23 19:05:33
【问题描述】:
df1:
campaign_name campaign_team
einsurancep09 other
estoreemicardcdwpnov06 other
estoreemicardwmnov06 other
estoreemicardgenericspnov06 other
df2:
terms product_category product
insurance insurance null
def emi store
ab bhi asd
de lic cards
a credit cards
以下是我的场景:
- '
terms'列(df2)按字符串长度降序排列。 - 应与
contains/like的df1 的campaign_name进行比较。 - 无论
terms字符串matches first与campaign_name,其product_category 和product 都应被拾取并应作为新列添加到df1 中。 - 对于
campaign_name值“einsurancep09”,来自terms的“insurance”值包含在campaign_name 中,因此它的product_category 和product 被拾取并作为df1 添加到输出中。 - 另一个例子:考虑其余3条记录,其中
containdef、ab和de在campaign_name字符串中,但我们选择product_category和“def”的产品作为appeared first与“ab”和“de”相比,是longest in the length
下面是我的代码:
df1 = df1.withColumn("product_category",when(df1.campaign_name.contains(df2.terms),df2.product_category).otherwise('other'))
但是,它给了我以下错误:
raise converted from None
pyspark.sql.utils.AnalysisException: Resolved attribute(s) terms#37,product_category#38 missing from campaign_name#16,campaign_team#17 in operator !Project [campaign_name#16, campaign_team#17, CASE WHEN Contains(campaign_name#16, terms#37) THEN product_category#38 ELSE other END AS product_category#44].;
!Project [campaign_name#16, campaign_team#17, CASE WHEN Contains(campaign_name#16, terms#37) THEN product_category#38 ELSE other END AS product_category#44]
+- Relation[campaign_name#16,campaign_team#17] csv
那么我哪里错了?
根据堆栈的回答,我得到以下输出:
+---------------+-------------+---------+----------------+-------+
|campaign_name |campaign_team|terms |product_category|product|
+---------------+-------------+---------+----------------+-------+
|einsurancepnm06|other |insurance|Insurance |NaN |
+---------------+-------------+---------+----------------+-------+
【问题讨论】:
-
可以分享文本格式的示例
-
你想让我怎么分享?
-
"de" 也与campaign_name 中的所有记录匹配。为什么它不包含在输出中。
-
当您粘贴问题时.. 使其“粘贴为纯文本”..
-
好的。问题是无论哪个字符串满足“包含”要求,都应该提取其相关值,这就是为什么这里不考虑“de”和“abc”的原因。
标签: python pandas apache-spark pyspark apache-spark-sql