2016-08-08 24 views
4

我正在嘗試將多個交叉表合併爲一個。請注意,提供的數據顯然僅用於測試目的。實際數據要大得多,所以效率對我來說非常重要。在Python中合併交叉表

交叉表生成,列出,然後在word列中與lambda函數合併。但是,這種合併的結果並不是我期望的結果。我認爲問題在於,即使使用dropna = False,交叉表的值僅爲NA的列也會被丟棄,這會導致merge函數失敗。我將首先展示代碼,然後介紹中間數據和錯誤。

import pandas as pd 
import numpy as np 
import functools as ft 

def main(): 
    # Create dataframe 
    df = pd.DataFrame(data=np.zeros((0, 3)), columns=['word','det','source']) 
    df["word"] = ('banana', 'banana', 'elephant', 'mouse', 'mouse', 'elephant', 'banana', 'mouse', 'mouse', 'elephant', 'ostrich', 'ostrich') 
    df["det"] = ('a', 'the', 'the', 'a', 'the', 'the', 'a', 'the', 'a', 'a', 'a', 'the') 
    df["source"] = ('BE', 'BE', 'BE', 'NL', 'NL', 'NL', 'FR', 'FR', 'FR', 'FR', 'FR', 'FR') 

    create_frequency_list(df) 

def create_frequency_list(df): 
    # Create a crosstab of ALL values 
    # NOTE that dropna = False does not seem to work as expected 
    total = pd.crosstab(df.word, df.det, dropna = False) 
    total.fillna(0) 
    total.reset_index(inplace=True) 
    total.columns = ['word', 'a', 'the'] 

    crosstabs = [total] 

    # For the column headers, multi-level 
    first_index = [('total','total')] 
    second_index = [('a','the')] 

    # Create crosstabs per source (one for BE, one for NL, one for FR) 
    # NOTE that dropna = False does not seem to work as expected 
    for source, tempDf in df.groupby('source'): 
     crosstab = pd.crosstab(tempDf.word, tempDf.det, dropna = False) 
     crosstab.fillna(0) 
     crosstab.reset_index(inplace=True) 
     crosstab.columns = ['word', 'a', 'the'] 
     crosstabs.append(crosstab) 

     first_index.extend((source,source)) 
     second_index.extend(('a','the')) 

    # Just for debugging: result as expected 
    for tab in crosstabs: 
     print(tab) 

    merged = ft.reduce(lambda left,right: pd.merge(left,right, on='word'), crosstabs).set_index('word') 

    # UNEXPECTED RESULT 
    print(merged)  

    arrays = [first_index, second_index] 

    # Throws error: NotImplementedError: > 1 ndim Categorical are not supported at this time 
    columns = pd.MultiIndex.from_arrays(arrays) 

    df_freq = pd.DataFrame(data=merged.as_matrix(), 
         columns=columns, 
         index = crosstabs[0]['word']) 
    print(df_freq) 

main() 

個人交叉表:並不如預期。 NA列被丟棄

 word a the 
0 banana 2 1 
1 elephant 1 2 
2  mouse 2 2 
3 ostrich 1 1 

     word a the 
0 banana 1 1 
1 elephant 0 1 

     word a the 
0 banana 1 0 
1 elephant 1 0 
2  mouse 1 1 
3 ostrich 1 1 

     word a the 
0 elephant 0 1 
1  mouse 1 1 

這意味着數據幀不會共享所有值,而這又會導致合併混亂。

合併

# NotImplementedError: > 1 ndim Categorical are not supported at this time 
columns = pd.MultiIndex.from_arrays(arrays) 

所以據我可以告訴這個問題早開始:未如預期,顯然

  a_x the_x a_y the_y a_x the_x a_y the_y 
word              
elephant 1  2 0  1 1  0 0  1 

但是,錯誤只得到在列分配拋出,與新加坡協定,並使整個事情失敗。但是,由於我在Python中經驗不足,所以我無法確定。

我期待什麼,是一個多指標輸出:

source  total  BE   FR   NL 
    det   a the  a the  a the  a the 
    word 
0 banana  2 1  1 1  1 0  0 0 
1 elephant 1 2  0 1  1 0  0 1 
2 mouse  2 2  0 0  1 1  1 1 
3 ostrich  1 1  0 0  1 1  0 0 

回答

2

我決定給你讓你你想要什麼更好的辦法:因爲我pd.crosstab因爲我用df.groupby([col1, col2]).size().unstack()來代理

一般規則。您正在嘗試爲source的每個組執行一次交叉表。我可以很好地適應與我現有的組df.groupby([col1, col2, col3]).size().unstack([2, 1])

sort_index(1).fillna(0).astype(int)只是爲了漂亮的事情。

如果你想更好地理解。試試下面的東西,看看你會得到什麼:

  • df.groupby(['word', 'gender']).size()
  • df.groupby(['word', 'gender', 'source']).size()

unstackstack方便的方式來獲得的東西,是在索引中的列,而不是反之亦然。 unstack([2, 1])指定索引級別取消堆棧的順序。

最後,我再次拿我的xtabsstack並跨行並unstack準備到pd.concat。 Voilà!

xtabs = df.groupby(df.columns.tolist()).size() \ 
      .unstack([2, 1]).sort_index(1).fillna(0).astype(int) 

pd.concat([xtabs.stack().sum(1).rename('total').to_frame().unstack(), xtabs], axis=1) 

enter image description here

代碼現在應該是這樣的:

import pandas as pd 
import numpy as np 
import functools as ft 

def main(): 
    # Create dataframe 
    df = pd.DataFrame(data=np.zeros((0, 3)), columns=['word','gender','source']) 
    df["word"] = ('banana', 'banana', 'elephant', 'mouse', 'mouse', 'elephant', 'banana', 'mouse', 'mouse', 'elephant', 'ostrich', 'ostrich') 
    df["gender"] = ('a', 'the', 'the', 'a', 'the', 'the', 'a', 'the', 'a', 'a', 'a', 'the') 
    df["source"] = ('BE', 'BE', 'BE', 'NL', 'NL', 'NL', 'FR', 'FR', 'FR', 'FR', 'FR', 'FR') 

    return create_frequency_list(df) 

def create_frequency_list(df): 
    xtabs = df.groupby(df.columns.tolist()).size() \ 
       .unstack([2, 1]).sort_index(1).fillna(0).astype(int) 

    total = xtabs.stack().sum(1) 
    total.name = 'total' 
    total = total.to_frame().unstack() 

    return pd.concat([total, xtabs], axis=1) 

main() 
+0

謝謝你的努力至今。你能解釋我應該把它放在哪裏嗎?它嘗試刪除'create_frequency_list'中的所有內容並將其替換爲您的代碼,但在代碼的最後一行出現錯誤''str'對象不可調用'。除此之外,你還可以更徹底地解釋你的代碼中發生了什麼?正如我所說我是初學者,但我非常渴望學習。 –

+0

@BramVanroy我更新了我的帖子。 – piRSquared

+0

我複製粘貼你的代碼,我仍然得到相同的錯誤。這是[分解](http://pastebin.com/NQwLhp6R)。運行Python 3.4.3。 –