用 nan 替换常量值

Replacing constant values with nan

import pandas as pd
data={'col1':[1,3,3,1,2,3,2,2]}
df=pd.DataFrame(data,columns=['col1'])
print df


     col1  
0     1          
1     3          
2     3          
3     1          
4     2          
5     3          
6     2          
7     2    
Expected result:
      Col1 newCol1
0    1.      1
1    3.      3
2    3.      NaN
3.   1.      1
4    2.      2
5    3.      3
6    2.      2
7.   2.      Nan

尝试 where 结合 shift

df['col2'] = df.col1.where(df.col1.ne(df.col1.shift()))
df
Out[191]: 
   col1  col2
0     1   1.0
1     3   3.0
2     3   NaN
3     1   1.0
4     2   2.0
5     3   3.0
6     2   2.0
7     2   NaN