user7712225
user7712225

Reputation: 55

Pandas: use apply function based on another column condition

I want to use apply() function on first column for only particular cases of values from second column.

Suppose I have a dataframe like this

URL      text  
-------  ---------
URL1     
URL2     some text

I want to use apply() function on the URL column when text is blank (or some other condition). I have tried this

webdata['text'] = webdata.apply(lambda row: func(row['URL']) if row['text']== '' else row['text'])  

func() is my function I want to call. But I get this error.

('text', u'occurred at index key')

Is there any mistake, or is there better way to do it?

Upvotes: 2

Views: 1225

Answers (1)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210822

IIUC:

webdata.loc[webdata['text']=='', 'text'] = \
    webdata.loc[webdata['text']=='', 'URL'].apply(func) 

Upvotes: 1

Related Questions