我是Python的新手,我正在尝试使用索引来获取每一行的姓氏。
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
我在做什么错,有人吗?
答案 0 :(得分:1)
使用filter
逐行填充缺失值的每一行,最后按位置填充最后一列:
s = df.filter(like='Name').ffill(axis=1).iloc[:,-1]
print (s)
0 Jerico
1 Sarah
2 Thomas
Name: L3_Name, dtype: object
答案 1 :(得分:0)
我认为这可行
def manager(vec):
return vec.dropna().iloc[-2]