我有一个简单的函数,可以确定字符串是否包含子字符串。
def scoring_names(string, substring1, substring2, substring3):
"""Simple function to calculate the substrings in a string"""
score_list=[]
sub1 = string.count(substring1)
score_list.append(sub1)
sub2 = string.count(substring2)
score_list.append(sub2)
sub3 = string.count(substring3)
score_list.append(sub3)
#print(score_list)
return sum(score_list)
我也有一个数据框:
import pandas as pd
# data
data = [['James', 'Bond','Crazy','james_bond_fox'],
['John','Smith','Blackhand','davinchi_84'],
['Jose','Romero', 'Bear','jose.gamez']]
# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['Str_1', 'Str_2', 'Str_3', 'String'])
在数据框上应用该功能时-我看到以下错误:
TypeError: list indices must be integers or slices, not str
AttributeError: 'RangeIndex' object has no attribute 'levels'
有人可以建议我如何解决问题吗?
答案 0 :(得分:1)
为我工作。
df.apply(lambda x: scoring_names(x['String'],x['Str_1'],x['Str_2'],x['Str_3']),axis=1)
尽管如此,您可能需要进行一些区分大小写的调整,例如像这样:
def scoring_names(string, substring1, substring2, substring3):
"""Simple function to calculate the substrings in a string"""
string = string.lower()
substring1 = substring1.lower()
substring2 = substring2.lower()
substring3 = substring3.lower()
score_list=[]
sub1 = string.count(substring1)
score_list.append(sub1)
sub2 = string.count(substring2)
score_list.append(sub2)
sub3 = string.count(substring3)
score_list.append(sub3)
#print(score_list)
return sum(score_list)