【问题标题】:Need to create a new variable based on specific Condition in Python需要根据 Python 中的特定 Condition 创建一个新变量
【发布时间】:2018-02-28 07:34:03
【问题描述】:

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

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"
construction= "Masonry"时我想要Category="Mason"

感谢您的帮助!!

【问题讨论】:

    标签: python python-3.x pandas dataframe


    【解决方案1】:

    如果需要tree 并且如果条件失败mason,您似乎需要numpy.wherecontains 创建的条件:

    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)
    

    【讨论】:

    • @Sandy - 你想要测试子串吗?
    猜你喜欢
    • 2015-09-24
    • 1970-01-01
    • 2014-05-19
    • 1970-01-01
    • 2012-11-01
    • 2019-11-11
    • 2019-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多