【问题标题】:Str attribute error when using .apply() on a pandas series在熊猫系列上使用 .apply() 时出现 Str 属性错误
【发布时间】:2022-01-19 21:21:12
【问题描述】:

我有一个如下的df:

data = {'Internal':  ['unpaid second interator 4,000 USD and $50 third', '35 $ unpaid', "all good"],
        'Name': ['Charlie', 'Rodolf', 'samuel']}

df = pd.DataFrame(data)

print (df)

我想用 .apply() 运行这个公式:

def unspent(row):
    if row['Internal'].str.contains('unspent',case=False)==True:
        val="unspent in text"
    else:
        val="unspent is NOT in text"
    return val

& 得到一个带有附加列的表格:


df['Unspent']=df.apply(unspent,axis=1)

但我得到了一个错误:

AttributeError: 'str' object has no attribute 'str'

我尝试在公式def unspent 中省略.str. 并得到另一个错误:

AttributeError: 'str' object has no attribute 'contains'

【问题讨论】:

    标签: python python-3.x pandas apply


    【解决方案1】:

    问题是,您正在尝试对字符串使用 str.contains,它是 pandas Series 方法(因为 row['Internal'] 是每个 row 的字符串)

    你可以做的是替换

    if row['Internal'].str.contains('unspent',case=False)==True:
    

    if 'unspent' in row['Internal']:
    

    在您的函数中或在df['Internal'] 列上使用str.contains 创建一个布尔系列并使用np.where 选择值:

    df['Unspent'] = np.where(df['Internal'].str.contains('unspent', case=False), "unspent in text", "unspent is NOT in text")
    

    输出:

                                     Internal     Name  \
    0  unpaid second interator 4,000 USD and $50 third  Charlie   
    1                                      35 $ unpaid   Rodolf   
    2                                         all good   samuel   
    
                      Unspent  
    0  unspent is NOT in text  
    1  unspent is NOT in text  
    2  unspent is NOT in text  
    

    【讨论】:

      猜你喜欢
      • 2020-04-05
      • 1970-01-01
      • 2015-01-31
      • 1970-01-01
      • 2015-04-07
      • 1970-01-01
      • 2014-11-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多