需要根据PYTHON中的特定条件创建一个新变量:

问题描述 投票:-1回答:1

I am using below code

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而不是'==',因为它可能在Construction列中包含多个单词/字符串。它每次都给“树”。当建筑=“砌体”时,我想要Category =“Mason”

谢谢你的帮助!!

python python-3.x pandas dataframe
1个回答
0
投票

似乎你需要numpy.where与条件由contains创建,如果需要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)
© www.soinside.com 2019 - 2024. All rights reserved.