简体   繁体   中英

Apply function on python data frame - on each cell on a specific column, by other columns

I have this df -

sentence        idx 
a b c           1
d k t           0

and I want to add a tag to each sentence on the idx word,

sentence        
a <ref>b</ref> c          
<ref>d</ref> k t         

means I want to apply some function on each cell on column "sentence", with the information that is in another column - "idx".

for example with this function:

def add_tags_to_sentence(sentence, idx):
    split_sentence = sentence.split(' ')
    split_sentence[idx] = "<ref>" + split_sentence[idx] + "</ref>"
    return " ".join(split_sentence) 

Thank you

You can try this -

def add_tags_to_sentence(inp):
    inp = inp.values
    sentence = inp[0]
    idx = inp[1]
    split_sentence = sentence.split(' ')
    split_sentence[idx] = "<ref>" + split_sentence[idx] + "</ref>"
    return " ".join(split_sentence)

Then use it with apply with axis=1

df['sentence'] = df[['sentence','idx']].apply(add_tags_to_sentence,axis=1)

Data:

df = pd.DataFrame({
    "sentence" : ['a b c', 'd k t'],
    "idx"      : [1,0]
})

df:

  sentence  idx
0    a b c    1
1    d k t    0
def fun(x):
    x1 = x.sentence.split()
    x2 = "<ref>" + x1[x['idx']] + "</ref>"
    x1[x['idx']] = x2
    return ' '.join(x1)
df.apply(fun, axis=1)
0    a <ref>b</ref> c
1    <ref>d</ref> k t
dtype: object

Any function can be applied using dataFrame_name[column].apply(func_name) function, where columns is the one you want to apply the function to. NOTE: func_name in .apply() does not have brackets at its end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM