1

I am new to Python and I am trying to use indexing to obtain the last name along each row.

import numpy as np import pandas as pd def manager(vec): for i,val in enumerate(vec): if val == np.NaN: break return vec[i - 1] df = pd.DataFrame({'ID':[23,15,20], 'L1_name': ['Andrew','Thomas','Thomas'], 'L1_ID': [234,994,994],'L2_Name':['Andrew','Alice','Thomas'],'L2_ID':[234,237,994], 'L3_Name':['Jerico','Sarah',np.nan],'L3_ID':[453,237,np.nan]}) df['new'] = df.apply(manager, axis=1) df 

What am i doing wrongly, anyone?

1
  • your code ist probably not correctly formated. Your function manager returns in the first round of the foor loop, either with vec[- 1] or None. Commented Feb 20, 2019 at 12:15

2 Answers 2

1

Use filter with forward filling per rows of missing values with seelct last column by positions:

s = df.filter(like='Name').ffill(axis=1).iloc[:,-1] print (s) 0 Jerico 1 Sarah 2 Thomas Name: L3_Name, dtype: object 
Sign up to request clarification or add additional context in comments.

Comments

0

I think this works

def manager(vec): return vec.dropna().iloc[-2] 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.