2017-06-16 53 views
0

我目前使用熊貓和Python來處理大部分重複任務,我需要爲我的碩士論文完成。此時,我已經編寫了一些代碼(在堆棧溢出的幫助下),根據一個文件中的某些事件日期,找到在另一個文件中用作日期範圍的開始日期和結束日期。然後這些日期被定位並附加到一個空的列表中,然後我可以輸出到excel。但是,使用下面的代碼,我得到了一個有5列和400.000行的數據框(這基本上是我想要的),但不是我希望輸出的數據如何。下面是我的代碼:使用熊貓自動切片產品

end_date = pd.DataFrame(data=(df_sample['Date']-pd.DateOffset(days=2))) 
start_date = pd.DataFrame(data=(df_sample['Date']-pd.offsets.BDay(n=252))) 

merged_dates = pd.merge(end_date,start_date,left_index=True,right_index=True) 

ff_factors = [] 

for index, row in merged_dates.iterrows(): 
    time_range= (df['Date'] > row['Date_y']) & (df['Date'] <= row['Date_x']) 
    df_factor = df.loc[time_range] 
    ff_factors.append(df_factor) 

appended_data = pd.concat(ff_factors, axis=0) 

我需要的數據爲5列和250行(列是可變標識符)並排的,以便輸出,當它到excel我有,例如列AD,然後250每列的行數。這隨後需要重複列E-H等。使用ILOC,我可以定位使用appended_data.iloc[0:250] 250個觀察,與兩個5列和250行,然後將其輸出到Excel。

是任何方式對我的過程自動化,從而使選擇第一250和將其輸出到Excel之後,選擇下一個250並且將其輸出旁邊的第一250等?

我希望以上內容精確清晰,否則我很樂意詳細說明!

編輯:

My entire dataframe

以上圖片說明什麼,我得到輸出到Excel時; 5列和407.764行。我需要的是將這種拆分分解爲以下幾種方式: Using iloc[0:250] on the entire smaple

第二張圖片說明了我如何將總樣本拆分。前五列和相應的250行需要作爲第二張照片。當我使用iloc [250:500]進行下一個分割時,我將得到接下來的250行,需要在最初的五列之後添加,等等。

+0

如果我解釋這個正確的,你要使用具有250行和1600十歲上下的列單excel表格中結束了? –

+0

基本上可以,大概是8000列左右,每列250列。前5列im描述涉及單個日期/觀察,因此列的總數應該是大約8000. –

+0

您可以在您要查找的縮小版本中編輯嗎?在'df之後'說'3','20'之前說'''',在15之後'說4行' – EFT

回答

0

您可以用np.reshape組合,可以做出的行爲做到這一點根據需要對單獨列這應該是比通過行的循環更快,並且pd.concat,加入它使dataframes一起回來:

def reshape_appended(df, target_rows, pad=4): 
    df = df.copy() # don't modify in-place 
    # below line adds strings, '0000',...,'0004' to the column names 
    # this ensures sorting the columns preserves the order 
    df.columns = [str(i).zfill(pad)+df.columns[i] for i in range(len(df.columns))] 
    #target number of new columns per column in df 
    target_cols = len(df.index)//target_rows 
    last_group = pd.DataFrame() 
    # below conditional fires if there will be leftover rows - % is mod 
    if len(df.index)%target_rows != 0: 
     last_group = df.iloc[-(len(df.index)%target_rows):].reset_index(drop=True) 
     df = df.iloc[:-(len(df.index)%target_rows)] # keep rows that divide nicely 
    #this is a large list comprehension, that I'll elaborate on below 
    groups = [pd.DataFrame(df[col].values.reshape((target_rows, target_cols), 
                order='F'), 
          columns=[str(i).zfill(pad)+col for i in range(target_cols)]) 
       for col in df.columns] 
    if not last_group.empty: # if there are leftover rows, add them back 
     last_group.columns = [pad*'9'+col for col in last_group.columns] 
     groups.append(last_group) 
    out = pd.concat(groups, axis=1).sort_index(axis=1) 
    out.columns = out.columns.str[2*pad:] # remove the extra characters in the column names 
    return out 

last_group採取不整除任何行的護理成套250.用列名玩弄執行正確的排序順序。

df[col].values.reshape((target_rows, target_cols), order='F') 

重塑中的值的列的df到由元組(target_rows, target_cols)指定的形狀col,與訂貨的Fortran用途,通過F表示。

columns=[str(i).zfill(pad)+col for i in range(target_cols)] 

只是給這些列命名,任何事情都可以在後面建立正確的排序。

例:

df = pd.DataFrame(np.random.randint(0, 10, (23, 3)), columns=list('abc')) 

reshape_appended(df, 5) 
Out[160]: 
    a b c a b c a b c a b c a b c 
0 8 3 0 4 1 9 5 4 7 2 3 4 5.0 7.0 2.0 
1 1 6 1 3 5 1 1 6 0 5 9 4 6.0 0.0 1.0 
2 3 1 3 4 3 8 9 3 9 8 7 8 7.0 3.0 2.0 
3 4 0 1 5 5 6 6 4 4 0 0 3 NaN NaN NaN 
4 9 7 3 5 7 4 6 5 8 9 5 5 NaN NaN NaN 

df 
Out[161]: 
    a b c 
0 8 3 0 
1 1 6 1 
2 3 1 3 
3 4 0 1 
4 9 7 3 
5 4 1 9 
6 3 5 1 
7 4 3 8 
8 5 5 6 
9 5 7 4 
10 5 4 7 
11 1 6 0 
12 9 3 9 
13 6 4 4 
14 6 5 8 
15 2 3 4 
16 5 9 4 
17 8 7 8 
18 0 0 3 
19 9 5 5 
20 5 7 2 
21 6 0 1 
22 7 3 2 
+0

謝謝你的答案@EFT。作爲即時通訊仍然學習Python和熊貓,這看起來有點複雜。我將不得不使用它來了解發生了什麼。感謝您的時間! –

+0

@MBV_DK我會添加評論。 – EFT

+0

我一直在玩這個函數,現在我一直在得到一個ValueError:在運行reshape_appended(attached_data,250,pad = 4)之後,無法將大小爲14的數組重新整形(250,1631)。這可能是由於attached_data的總大小?例如行數未被均勻分配250? –

0

我最好的猜測來解決問題是嘗試和循環,直到計數器大於長度,所以

i = 250 # counter 
j = 0 # left limit 

for x in range(len("your dataframe")): 
    appended_data.iloc[j:i] 
    i+=250 
    if i > len("your df"): 
     appended_data.iloc[j:(len("your df")) 
     break 
    else: 
     j = i 
+0

謝謝艾哈邁德!我看起來像我在找什麼。我有個問題,當你寫「你的數據框」時,你是指一個新的數據框? –

+0

不,這是你已經做了,我只是不斷忘記它的名字,所以我寫了:) – Ahmed

+0

哦,好吧!這是因爲你指的是iloc方法中的attached_data,它是當前持有所有數據的數據框:) –