[英]Apply a function to data frame
我有一个简单的 function 确定字符串是否包含子字符串。
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'])
当我在数据框上应用 function 时 - 我看到以下错误:
TypeError: list indices must be integers or slices, not str
AttributeError: 'RangeIndex' object has no attribute 'levels'
谁能建议我如何解决这些问题?
为我工作。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.