2017-08-09 83 views
1

我用熊貓: 輸入:蟒蛇大熊貓下一行的值轉移

import pandas as pd 
a=pd.Series([0,0,1,0,0,0,0]) 

輸出:

0 0 
1 0 
2 1 
3 0 
4 0 
5 0 
6 0 

我想在相同的價值觀下一行的數據:

輸出:

0 0 
1 0 
2 1 
3 1 
4 1 
5 1 
6 0 

使用

a+a.shift(1)+a.shift(2)+a.shift(3) 

我覺得這是不是一個聰明的解決方案 誰擁有這個

回答

0

一個聰明的解決方案,您可以試試這個假設指數6應該是價值1

a=pd.Series([0,0,1,0,0,0,0]) 
a.eq(1).cumsum() 

Out[19]: 
0 0 
1 0 
2 1 
3 1 
4 1 
5 1 
6 1 
dtype: int32 

更新:不止一個值不等於0.

a=pd.Series([0,0,1,0,1,3,0]) 
a.ne(0).cumsum() 
A=pd.DataFrame({'a':a,'Id':a.ne(0).cumsum()}) 
A.groupby('Id').a.cumsum() 


Out[58]: 
0 0 
1 0 
2 1 
3 1 
4 1 
5 3 
6 3 

或者你可以使用ffill

a[a.eq(0)]=np.nan 
a.ffill().fillna(0) 

Out[64]: 
0 0.0 
1 0.0 
2 1.0 
3 1.0 
4 1.0 
5 3.0 
6 3.0 
+0

可以做'cumsum'任何理由'EQ(1)'按位比較呢? –

+0

@AlexanderMFFarlane更新。但你是對的,以前的方法不需要'eq' – Wen

0

1你可以過濾系列 「的」 值(SearchValue)。

2重新指數dataseries到待說明長度(LengthOfIndex)和正填補「你」給定的次數(LengthOfFillRange)

3個零再填寫一次。

import pandas as pd 
import numpy as np 
a=pd.Series([0,0,1,0,0,0,0]) 
SearchValue  = 1 
LengthOfIndex  = 7 
LengthOfFillRange = 4 
a=a[a==SearchValue]\ 
    .reindex(np.linspace(1,LengthOfIndex,LengthOfIndex, dtype='int32'), 
       method='ffill', 
       limit=LengthOfFillRange)\ 
    .fillna(0) 
0

如果你需要通過一些限制使用replaceNaN s,則ffillfillna與方法ffill)和最後fillna重複只有2個值系列的轉換NaN s到原始值(如果必要,轉換爲int) :

a=pd.Series([0,0,1,0,0,0,0,1,0,0,0,]) 
print (a) 
0  0 
1  0 
2  1 
3  0 
4  0 
5  0 
6  0 
7  1 
8  0 
9  0 
10 0 
dtype: int64 

b= a.replace(0,np.nan).ffill(limit=2).fillna(0).astype(a.dtype) 
print (b) 
0  0 
1  0 
2  1 
3  1 
4  1 
5  0 
6  0 
7  1 
8  1 
9  1 
10 0 
dtype: int64