【问题标题】:How to search multiple string in column and update cell vales?如何在列中搜索多个字符串并更新单元格值?
【发布时间】:2021-12-25 10:15:50
【问题描述】:

我一直在尝试根据另一个包含字符串的列值来更新数据框中的列值。

import pandas as pd
import numpy as np

1.   df=pd.read_excel('C:\\Users\\bahlrajesh23\\datascience\\Invoice.xlsx')
2.   df1 =( df[df['Vendor'].str.contains('holding')] )
3.   df['cat'] = pd.np.where(df['Vendor'].str.contains('holding'),"Yes",'' )
4.   print(df[0:5])

上面第 4 行的代码运行良好,但现在我想在第 3 行添加更多条件,我像这样修改了上面的第 3 行。

df['cat'] = pd.np.where((df['Vendor'].str.contains('holding'),"Yes",''),
                        (df['Vendor'].str.contains('tech'),"tech",''))

我收到以下错误

ValueError: either both or neither of x and y should be given

我怎样才能做到这一点?

【问题讨论】:

    标签: python pandas dataframe search contains


    【解决方案1】:

    因为您希望针对每个条件返回不同的答案,所以使用 np.where() 将不起作用。 map() 也很难。

    您可以使用apply() 并根据需要使函数变得复杂。

    df = pd.DataFrame({'Vendor':['techi', 'tech', 'a', 'hold', 'holding', 'holdingon', 'techno', 'b']})
    df
    
    def add_cat(x):
        if 'tech' in x:
            return 'tech'
        if'holding' in x:
            return 'Yes'
        else:
            return ''
            
    df['cat'] = df['Vendor'].apply(add_cat)
    
          Vendor   cat
    0      techi  tech
    1       tech  tech
    2          a
    3       hold
    4    holding   Yes
    5  holdingon   Yes
    6     techno  tech
    7          b
    

    【讨论】:

    • 我是这样写的
    • 这不起作用,因为当我在我的数据框列中应用此函数时,它会给出错误“TypeError:'float' 类型的参数不可迭代”。这意味着您的解决方案只有在一切都是文本时才有效。
    • 那么请添加您的数据的代表性示例。或者将您的浮动更改为文本。不清楚为什么要在浮动元素中搜索文本。
    猜你喜欢
    • 2021-02-17
    • 1970-01-01
    • 2019-09-15
    • 2021-11-19
    • 2018-07-15
    • 2015-12-14
    • 1970-01-01
    • 2016-03-21
    • 1970-01-01
    相关资源
    最近更新 更多