Lambda not in function 不适用于 Python 中的多个单词
Lambda not in function doesn't work for more than one word in Python
如果条件
我想通过 lambda 过滤数据帧
我有一个“产品名称”和“类别 1”列,并且“如果产品名称”不包含(“拳击手”,“拳击手”,“袜子”,“袜子”)我想更改“类别 1” ”列为“其他”,但下面的代码将它们全部更改为“其他”示例甚至包含“袜子”
df = pd.DataFrame({
'product_name': ["blue shirt", " medium boxers", "red jackets ", "blue sock"],})
df["category1"]=df.apply(lambda x: "Other" if ("boxer","boxers","sock","socks" not in x["product_name"] ) else x["category1"], axis=1)
我预计结果如下
df = pd.DataFrame({
'product_name': ["blue shirt", " medium boxers", "red jackets ", "blue sock"],
'category1'["other", Nan, "other ", "Nan"],})
感谢您的支持
您可以使用 str.contains
:
items = ("boxer","boxers","sock","socks")
import numpy as np
df["category1"] = np.where(df['product_name'].str.contains('|'.join(items)),
np.nan, # value is True
'Other') # value if False
输出:
product_name category1
0 blue shirt Other
1 medium boxers nan
2 red jackets Other
3 blue sock nan
如果条件
我想通过 lambda 过滤数据帧我有一个“产品名称”和“类别 1”列,并且“如果产品名称”不包含(“拳击手”,“拳击手”,“袜子”,“袜子”)我想更改“类别 1” ”列为“其他”,但下面的代码将它们全部更改为“其他”示例甚至包含“袜子”
df = pd.DataFrame({
'product_name': ["blue shirt", " medium boxers", "red jackets ", "blue sock"],})
df["category1"]=df.apply(lambda x: "Other" if ("boxer","boxers","sock","socks" not in x["product_name"] ) else x["category1"], axis=1)
我预计结果如下
df = pd.DataFrame({
'product_name': ["blue shirt", " medium boxers", "red jackets ", "blue sock"],
'category1'["other", Nan, "other ", "Nan"],})
感谢您的支持
您可以使用 str.contains
:
items = ("boxer","boxers","sock","socks")
import numpy as np
df["category1"] = np.where(df['product_name'].str.contains('|'.join(items)),
np.nan, # value is True
'Other') # value if False
输出:
product_name category1
0 blue shirt Other
1 medium boxers nan
2 red jackets Other
3 blue sock nan