大熊猫按列顺序记录

时间:2017-12-07 21:03:16

标签: python pandas multiple-columns

我有这个df1:

ID  Name    Alias   Nickname
101 Robert  Rob Bob
201 Tom     
315     Megan   Meg
405 Teddy       Ted
510         Bill
602         

但我想在一个Result列中添加一个顺序中的条目(Name,Alias(如果Name为空),Nickname(如果Alias和Name都为空))

ID  Name    Alias   Nickname    Result
101 Robert  Rob Bob Robert
201 Tom         Tom
315     Megan   Meg Megan
405 Teddy       Ted Teddy
510         Bill    Bill
602             NA

1 个答案:

答案 0 :(得分:1)

试试这个。

df1['Result'] = df1[['Name', 'Alias', 'Nickname']].bfill(axis=1).iloc[:, 0]

Out [142]:    

    ID      Name    Alias   Nickname    Result
0   101     Robert  Rob     Bob         Robert
1   201     Tom     NaN     NaN         Tom
2   315     Megan   Meg     NaN         Megan
3   405     Teddy   Ted     NaN         Teddy
4   510     Bill    NaN     NaN         Bill
5   602     NaN     NaN     NaN         NaN