簡體   English   中英

將 function 應用於數據框

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM