Python 熊猫有条件地向上移动整个列

Python 熊猫有条件地向上移动整个列,python,pandas,Python,Pandas,我有以下数据帧 year dayofyear x 360 2014 361 109357.2798 361 2014 362 106484.6514 362 2014 363 112627.1748 363 2014 364 99750.2315 364 2014 365 56330.7660 365 2014 36

我有以下数据帧

     year  dayofyear            x      
360  2014        361  109357.2798  
361  2014        362  106484.6514   
362  2014        363  112627.1748   
363  2014        364   99750.2315   
364  2014        365   56330.7660  
365  2014        366          NaN  
366  2015          1   60859.1082   
367  2015          2   99507.1793    
368  2015          3   92279.8554  
369  2015          4  106590.6594   
我想将NaN下方“x”列中的所有值向上移动一个位置。“year”和“dayofyear”中的值应保持不变

因此,期望的输出如下所示:

     year  dayofyear            x      
360  2014        361  109357.2798  
361  2014        362  106484.6514   
362  2014        363  112627.1748   
363  2014        364   99750.2315   
364  2014        365   56330.7660  
365  2014        366   60859.1082  
366  2015          1   99507.1793   
367  2015          2   92279.8554     
368  2015          3  106590.6594  
369  2015          4   NaN  
我已经使用了pd.shift(-1),但是这改变了整个专栏。我只需要将NaN以下的值向后移动1,有人有好的解决方案吗?

这里有一种方法

In [401]: s = df['x'].isnull()

In [403]: df.loc[s[s].index[0]:, 'x'] = df['x'].shift(-1)

In [404]: df
Out[404]:
     year  dayofyear            x
360  2014        361  109357.2798
361  2014        362  106484.6514
362  2014        363  112627.1748
363  2014        364   99750.2315
364  2014        365   56330.7660
365  2014        366   60859.1082
366  2015          1   99507.1793
367  2015          2   92279.8554
368  2015          3  106590.6594
369  2015          4          NaN

细节

In [405]: s
Out[405]:
360    False
361    False
362    False
363    False
364    False
365     True
366    False
367    False
368    False
369    False
Name: x, dtype: bool

In [406]: s[s].index
Out[406]: Int64Index([365], dtype='int64')

In [407]: s[s].index[0]
Out[407]: 365
这里有一条路

In [401]: s = df['x'].isnull()

In [403]: df.loc[s[s].index[0]:, 'x'] = df['x'].shift(-1)

In [404]: df
Out[404]:
     year  dayofyear            x
360  2014        361  109357.2798
361  2014        362  106484.6514
362  2014        363  112627.1748
363  2014        364   99750.2315
364  2014        365   56330.7660
365  2014        366   60859.1082
366  2015          1   99507.1793
367  2015          2   92279.8554
368  2015          3  106590.6594
369  2015          4          NaN

细节

In [405]: s
Out[405]:
360    False
361    False
362    False
363    False
364    False
365     True
366    False
367    False
368    False
369    False
Name: x, dtype: bool

In [406]: s[s].index
Out[406]: Int64Index([365], dtype='int64')

In [407]: s[s].index[0]
Out[407]: 365