2016-10-16 9 views
2

내가 행 가장 긴 연속 번호가 조각을 반환 할팬더 dataframe는 -처럼 '안양'라는 팬더 dataframe와

   A 
2015-05-01 True 
2015-05-02 True 
2015-05-03 False 
2015-05-04 False 
2015-05-05 False 
2015-05-06 False 
2015-05-07 True 
2015-05-08 False 
2015-05-09 False 

다음 특정 조건에 가장 긴 연속 행을 찾을 경우 열 'A' '거짓'이라고 읽습니다. 이 작업을 수행 할 수 있습니까?

답변

3

을 사용하여 A 열의 변경 사항을 감지 할 수 있습니다. boolean은 파이썬에서 합계 될 수 있습니다.

# Test data 
df= DataFrame([True, True, False, False, False, False, True, False, False], 
       index=pd.to_datetime(['2015-05-01', '2015-05-02', '2015-05-03', 
            '2015-05-04', '2015-05-05', '2015-05-06', 
            '2015-05-07', '2015-05-08', '2015-05-09']), 
       columns=['A']) 

# We have to ensure that the index is sorted 
df.sort_index(inplace=True) 
# Resetting the index to create a column 
df.reset_index(inplace=True) 

# Grouping by the cumsum and counting the number of dates and getting their min and max 
df = df.groupby(df['A'].cumsum()).agg(
    {'index': ['count', 'min', 'max']}) 

# Removing useless column level 
df.columns = df.columns.droplevel() 

print(df) 
# count  min  max 
# A        
# 1  1 2015-05-01 2015-05-01 
# 2  5 2015-05-02 2015-05-06 
# 3  3 2015-05-07 2015-05-09 

# Getting the max 
df[df['count']==df['count'].max()] 

# count  min  max 
# A        
# 2  5 2015-05-02 2015-05-06 
+0

좋은,하지만 난 그 인덱스로 '날짜'를 사용하지 못할와 내가 df.index하려고하면 대신 나는 형식 오류를 얻을 : unhashable 유형을 'DatetimeIndex' –

+0

내 DF 실제로 dataframe을 가지고 sData로라는 개체입니다 'df'회원. 그래서 'index'를 시도하면 오류가 발생합니다. 'df.index'또는 'sData.df.index'를 시도하면 오류가 발생합니다. 난 단지 어떻게 작성 해야할지 모르겠다. agg 함수에서 'index'라고 쓰면된다. –

+0

@RunnerBean 내 예제에서 보여준 것처럼 색인을 먼저'df.reset_index (inplace = True)'로 재설정해야한다. – Romain