2014-02-10 48 views
0

我想從每個事件(級別1)中刪除前導零和尾隨零,但不包括非零數字所包圍的零。從基於列值和位置的熊貓分級系列中刪除行

中查找並刪除所有零以下工作:

df = events[event_no][events[event_no] != 0] 

我有以下的分級系列:

1 2/09/2010 0 
     3/09/2010 1.5 
     4/09/2010 4.3 
     5/09/2010 5.1 
     6/09/2010 0 
    2 1/05/2007 53.2 
     2/05/2007 0 
     3/05/2007 21.5 
     4/05/2007 2.5 
     5/05/2007 0 

和希望:

1 3/09/2010 1.5 
     4/09/2010 4.3 
     5/09/2010 5.1 
    2 1/05/2007 53.2 
     2/05/2007 0 
     3/05/2007 21.5 
     4/05/2007 2.5 

我已閱讀 Deleting DataFrame row in Pandas based on column valueFilter columns of only zeros from a Pandas data frame 但是在解決這個問題上一直不成功。

回答

0

你的dataframe是什麼樣的。無論如何,不​​應該有任何區別,簡單的布爾索引應該這樣做:

In [101]:print df 

Out [101]: 
        c1 
first second   
1  2/09/2010 0.0 
     3/09/2010 1.5 
     4/09/2010 4.3 
     5/09/2010 5.1 
     6/09/2010 0.0 
2  1/05/2007 53.2 
     2/05/2007 0.0 
     3/05/2007 21.5 
     4/05/2007 2.5 
     5/05/2007 0.0 


In [102]: 

is_edge=argwhere(hstack((0,diff([item[0] for item in df.index.tolist()])))!=0).flatten() 
is_edge=hstack((is_edge, is_edge-1, 0, len(df)-1)) 
g_idx=hstack(([item for item in argwhere(df['c1']==0).flatten() if item not in is_edge], 
       argwhere(df['c1']!=0).flatten())) 
print df.ix[sorted(g_idx)] 



Out[102]: 
        c1 
first second   
1  3/09/2010 1.5 
     4/09/2010 4.3 
     5/09/2010 5.1 
2  1/05/2007 53.2 
     2/05/2007 0.0 
     3/05/2007 21.5 
     4/05/2007 2.5 

如果你有series而不是dataframe,說該系列產品是s,您可以:

將其轉換爲一個dataframe

df=pd.DataFrame(s, columns=['c1']) 

或者:

In [113]: 
is_edge=argwhere(hstack((0,diff([item[0] for item in s.index.tolist()])))!=0).flatten() 
is_edge=hstack((is_edge, is_edge-1, 0, len(s)-1)) 
g_idx=hstack(([item for item in argwhere(s.values==0).flatten() if item not in is_edge], 
       argwhere(s.values!=0).flatten())) 
s[sorted(g_idx)] 
Out[113]: 
first second 
1  3/09/2010  1.5 
     4/09/2010  4.3 
     5/09/2010  5.1 
2  1/05/2007 53.2 
     2/05/2007  0.0 
     3/05/2007 21.5 
     4/05/2007  2.5 
dtype: float64 

BTW,我產生了系列:

In [116]: 
tuples=[(1, '2/09/2010'), 
(1, '3/09/2010'), 
(1, '4/09/2010'), 
(1, '5/09/2010'), 
(1, '6/09/2010'), 
(2, '1/05/2007'), 
(2, '2/05/2007'), 
(2, '3/05/2007'), 
(2, '4/05/2007'), 
(2, '5/05/2007')] 
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second']) 
s = pd.Series(array([0.,1.5,4.3,5.1,0.,53.2,0.,21.5,2.5,0.]), index=index) 
s 
Out[116]: 
first second 
1  2/09/2010  0.0 
     3/09/2010  1.5 
     4/09/2010  4.3 
     5/09/2010  5.1 
     6/09/2010  0.0 
2  1/05/2007 53.2 
     2/05/2007  0.0 
     3/05/2007 21.5 
     4/05/2007  2.5 
     5/05/2007  0.0 
dtype: float64 

我有相同的結構嗎?

+0

這與OP的期望輸出不匹配。 「我想從每個事件(等級1)中刪除前導零和尾隨零,但不包括非零數字包圍的零。」 – DSM

+0

我錯過了,不知道是否有更優雅的做法。無論如何,人們必須找到第一級的邊緣。這至少需要幾行。 –

+0

該解決方案要求第一級索引是數字。 –