2017-03-16 1 views
0

특정 컬럼에 판다 Dataframe에 패딩 데이터를 확인 :내가이처럼 보이는 DataFrame이

import numpy as np 
raw_data = {'Series_Date':['2017-03-10','2017-03-13','2017-03-14','2017-03-15'],'SP':[35.6,56.7,41,41],'1M':[-7.8,56,56,-3.4],'3M':[24,-31,53,5]} 
import pandas as pd 
df = pd.DataFrame(raw_data,columns=['Series_Date','SP','1M','3M']) 
print df 

나는이 DataFrame 특정 컬럼에 대한 테스트를 실행하고자하는 경우에만,이 목록에있는 모든 열 이름 :

check = {'1M','SP'} 
print check 

이 열에 대해서는이 열의 값이 전날의 값과 동일한 지 알고 싶습니다. 그래서 출력 dataframe는 (이 경우 :

output_data = {'Series_Date':['2017-03-14','2017-03-15'],'Comment':["Value for 1M data is same as previous day","Value for SP data is same as previous day"]} 
output_data_df = pd.DataFrame(output_data,columns = ['Series_Date','Comment']) 
print output_data_df 

당신은 어떻게 대처하는 몇 가지 지원을 제공하시기 바랍니다 수있는 예를 들어 같은 일련의 날짜와 코멘트를 반환해야합니까?

답변

0

가장 확실한 방법은 아닌지 잘 모르겠다. 그러나, 귀하의 의견

check = {'1M', 'SP'} 
prev_dict = {c: None for c in check} 

def check_prev_value(row): 
    global prev_dict 
    msg = "" 
    # MAYBE add clause to check if both are equal 
    for column in check: 
     if row[column] == prev_dict[column]: 
      msg = 'Value for %s data is same as previous day' % column 
     prev_dict[column] = row[column] 
    return msg 

df['comment'] = df.apply(check_prev_value, axis=1) 

output_data_df = df[df['comment'] != ""] 
output_data_df = output_data_df[["Series_Date", "comment"]].reset_index(drop=True) 

작동 :

Series_Date SP 1M 3M 
0 2017-03-10 35.6 -7.8 24 
1 2017-03-13 56.7 56.0 -31 
2 2017-03-14 41.0 56.0 53 
3 2017-03-15 41.0 -3.4 5 

출력은 다음과 같습니다

Series_Date         comment 
0 2017-03-14 Value for 1M data is same as previous day 
1 2017-03-15 Value for SP data is same as previous day 
+0

감사합니다 SP 나 SP와 3M과 같은 다른 열을 확인하려면 어떻게해야합니까? '열람'목록의 열마다 열을 테스트하도록 지정합니다. – sg91

+0

코드를 업데이트했습니다. 이제 체크에 표시되는 열을 검색합니다. – AndreyF

0

다음은 더 많거나 적은 당신이 원하는 않습니다. 값 전날의 여부와 같은 경우 열 item_ok 원래 dataframe 지정하는 추가된다

from datetime import timedelta 
df['Date_diff'] = pd.to_datetime(df['Series_Date']).diff() 
for item in check: 
    df[item+'_ok'] = (df[item].diff() == 0) & (df['Date_diff'] == timedelta(1)) 
df_output = df.loc[(df[[item + '_ok' for item in check]]).any(axis=1)] 
0

참조 : this answer

cols = ['1M','SP'] 
for col in cols: 
    df[col + '_dup'] = df[col].groupby((df[col] != df[col].shift()).cumsum()).cumcount() 

출력 열이 제로 (A)보다 큰 정수 것 중복이 발견되었습니다.

df: 

    Series_Date SP 1M 3M 1M_dup SP_dup 
0 2017-03-10 35.6 -7.8 24  0  0 
1 2017-03-13 56.7 56.0 -31  0  0 
2 2017-03-14 41.0 56.0 53  1  0 
3 2017-03-15 41.0 -3.4 5  0  1 

슬라이스 DUPS를 찾을 수 있습니다 : 여기

col = 'SP' 
dup_df = df[df[col + '_dup'] > 0][['Series_Date', col + '_dup']] 

dup_df: 

    Series_Date SP_dup 
3 2017-03-15  1 

가 (여러 열을 처리하는 추가 기능 사용) 위의 함수 버전입니다 :

import pandas as pd 
import numpy as np 

def find_repeats(df, col_list, date_col='Series_Date'): 
    dummy_df = df[[date_col, *col_list]].copy() 
    dates = dummy_df[date_col] 
    date_series = [] 
    code_series = [] 
    if len(col_list) > 1: 
     for col in col_list: 
      these_repeats = df[col].groupby((df[col] != df[col].shift()).cumsum()).cumcount().values 
      repeat_idx = list(np.where(these_repeats > 0)[0]) 
      date_arr = dates.iloc[repeat_idx] 
      code_arr = [col] * len(date_arr) 
      date_series.extend(list(date_arr)) 
      code_series.extend(code_arr) 
     return pd.DataFrame({date_col: date_series, 'col_dup': code_series}).sort_values(date_col).reset_index(drop=True) 
    else: 
     col = col_list[0] 
     dummy_df[col + '_dup'] = df[col].groupby((df[col] != df[col].shift()).cumsum()).cumcount() 
     return dummy_df[dummy_df[col + '_dup'] > 0].reset_index(drop=True) 

find_repeats(df, ['1M']) 

    Series_Date 1M 1M_dup 
0 2017-03-14 56.0  1 

find_repeats(df, ['1M', 'SP']) 

    Series_Date col_dup 
0 2017-03-14  1M 
1 2017-03-15  SP 

그리고 여기에 또 다른 방법입니다 팬더 사용 diff :

def find_repeats(df, col_list, date_col='Series_Date'): 
    code_list = [] 
    dates = list() 

    for col in col_list: 
     these_dates = df[date_col].iloc[np.where(df[col].diff().values == 0)[0]].values 
     code_arr = [col] * len(these_dates) 
     dates.extend(list(these_dates)) 
     code_list.extend(code_arr) 
    return pd.DataFrame({date_col: dates, 'val_repeat': code_list}).sort_values(date_col).reset_index(drop=True) 
관련 문제