需要根据Python中的特定条件创建新变量

2024-05-26 22:58:56 发布

您现在位置:Python中文网/ 问答频道 /正文

#我正在使用下面的代码#

for i in test.construction:
     if i.find("Wood"):
         test["Category"]="tree"

print (test[["construction", "Category"]])

输出: 建筑类别

            Masonry     tree
            Masonry     tree
               Wood     tree
               Wood     tree

我使用的是find而不是'==',因为它在构造列中可能包含多个单词/字符串。
它每次都给"tree"
我想要Category="Mason"construction= "Masonry"

谢谢你的帮助


Tags: 代码intesttreeforiffind类别
1条回答
网友
1楼 · 发布于 2024-05-26 22:58:56

如果需要tree并且如果条件失败mason,则需要^{}^{}创建的条件:

test['Category'] = np.where(test['construction'].str.contains('Wood'), 'tree', 'mason')
print (test)
  construction Category
0      Masonry    mason
1      Masonry    mason
2         Wood     tree
3         Wood     tree

或者,如果可能出现多种情况,请使用带有in的自定义函数作为测试子字符串:

def f(x):
    if 'Wood' in x:
        return 'tree'
    elif 'Masonry' in x:
        return 'mason'
    else:
        return x

test['Category'] = test['construction'].apply(f)

相关问题 更多 >

    热门问题