找出pandas中列中值的先前索引值

时间:2018-01-10 21:52:56

标签: python pandas

对于pandas数据框中的“stock”列,我想添加一个名为last_index的列,该列给出了给定Stock之前的索引值的值:

输入:

           Stock
02/10/17    IBM
02/10/17    Apple
02/10/17    Google
02/10/17    Microsoft
02/10/17    Lenova
02/10/17    Nintendo
02/10/17    Sony
02/10/17    Toshiba
03/10/17    IBM
03/10/17    Apple
03/10/17    Google
03/10/17    Microsoft
03/10/17    Lenova
03/10/17    Nintendo
03/10/17    Sony
03/10/17    BMW
03/10/17    Mercedes
04/10/17    Toshiba

输出:

               Stock    Last_index
02/10/17    IBM 
02/10/17    Apple   
02/10/17    Google  
02/10/17    Microsoft   
02/10/17    Lenova  
02/10/17    Nintendo    
02/10/17    Sony    
02/10/17    Toshiba 
03/10/17    IBM         02/10/17
03/10/17    Apple       02/10/17
03/10/17    Google      02/10/17
03/10/17    Microsoft   02/10/17
03/10/17    Lenova      02/10/17
03/10/17    Nintendo    02/10/17
03/10/17    Sony        02/10/17
03/10/17    BMW 
03/10/17    Mercedes    
04/10/17    Toshiba     02/10/17

非常感谢。

1 个答案:

答案 0 :(得分:6)

您可以使用 shift

df['New']=df.reset_index().groupby('Stock')['index'].shift().values
df
Out[472]: 
              Stock       New
02/10/17        IBM       NaN
02/10/17      Apple       NaN
02/10/17     Google       NaN
02/10/17  Microsoft       NaN
02/10/17     Lenova       NaN
02/10/17   Nintendo       NaN
02/10/17       Sony       NaN
02/10/17    Toshiba       NaN
03/10/17        IBM  02/10/17
03/10/17      Apple  02/10/17
03/10/17     Google  02/10/17
03/10/17  Microsoft  02/10/17
03/10/17     Lenova  02/10/17
03/10/17   Nintendo  02/10/17
03/10/17       Sony  02/10/17
03/10/17        BMW       NaN
03/10/17   Mercedes       NaN
04/10/17    Toshiba  02/10/17