![](/img/trans.png)
[英]combine two dataset and create new column based on specific condition in python
[英]Need to create a new variable based on specific Condition in 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
而不是'=='
因为它可能在 Construction 列中包含多个单词/字符串。
它每次都给"tree"
。
我想要Category="Mason"
when construction= "Masonry"
谢谢你的帮助!!
看来你需要numpy.where
条件由contains
if need tree
和 if condition fail 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.