2016-09-18 17 views
1

我有一個熊貓數據框,其中包含用戶學習期間參與者操作的每個對象的一行。每個參與者參與研究3次,每種條件(a,b,c)各一次,每種情況下與約300-700個對象一起工作。使用groupby和groupby.size()的輸出

當我報告工作的對象的數量時,我想確保這並沒有因條件而顯着變化(我不指望它已經完成,但需要統計確認)。

我想我想運行ANOVA來比較3個條件,但我無法弄清楚如何獲得我需要的ANOVA數據。

我目前有一些熊貓代碼來分組數據並計算每個參與者每條件的行數(所以我可以使用mean()和類似的方法來總結數據)。與所述數據的子集的示例如下:

>>> tmp = df.groupby([FIELD_PARTICIPANT, FIELD_CONDITION]).size() 
>>> tmp 
participant_id condition 
1    a   576 
2    b   367 
3    a   703 
4    c   309 
dtype: int64 

爲了計算ANOVA我通常只由條件柱,例如過濾這些

cond1 = tmp[tmp[FIELD_CONDITION] == CONDITION_A] 
cond2 = tmp[tmp[FIELD_CONDITION] == CONDITION_B] 
cond3 = tmp[tmp[FIELD_CONDITION] == CONDITION_C] 
f_val, p_val = scipy.stats.f_oneway(cond1, cond2, cond3) 

然而,由於tmpSeries而不是我習慣的DataFrame,我無法弄清楚如何以正常的方式實現這一目標。

>>> tmp[FIELD_CONDITION] 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/Library/Python/2.7/site-packages/pandas/core/series.py", line 583, in __getitem__ 
    result = self.index.get_value(self, key) 
    File "/Library/Python/2.7/site-packages/pandas/indexes/multi.py", line 626, in get_value 
    raise e1 
KeyError: 'condition' 
>>> type(tmp) 
<class 'pandas.core.series.Series'> 
>>> tmp.index 
MultiIndex(levels=[[u'1', u'2', u'3', u'4'], [u'd', u's']], 
      labels=[[0, 1, 2, 3], [0, 0, 0, 1]], 
      names=[u'participant_id', u'condition']) 

我確信這是解決一個簡單的問題,但我似乎無法得到有沒有一些幫助:)

回答

0

我想你需要reset_index然後輸出DataFrame

tmp = df.groupby([FIELD_PARTICIPANT, FIELD_CONDITION]).size().reset_index(name='count') 

樣品:

import pandas as pd 

df = pd.DataFrame({'participant_id': {0: 1, 1: 1, 2: 1, 3: 1, 4: 2, 5: 2, 6: 2, 7: 3, 8: 4, 9: 4}, 
        'condition': {0: 'a', 1: 'a', 2: 'a', 3: 'a', 4: 'b', 5: 'b', 6: 'b', 7: 'a', 8: 'c', 9: 'c'}}) 
print (df) 
    condition participant_id 
0   a    1 
1   a    1 
2   a    1 
3   a    1 
4   b    2 
5   b    2 
6   b    2 
7   a    3 
8   c    4 
9   c    4 

tmp = df.groupby(['participant_id', 'condition']).size().reset_index(name='count') 
print (tmp) 
    participant_id condition count 
0    1   a  4 
1    2   b  3 
2    3   a  1 
3    4   c  2 

如果需要與工作可以使用條件,其中由get_level_valuesMultiindexcondition水平的選擇值:

tmp = df.groupby(['participant_id', 'condition']).size() 
print (tmp) 
participant_id condition 
1    a   4 
2    b   3 
3    a   1 
4    c   2 
dtype: int64 

print (tmp.index.get_level_values('condition')) 
Index(['a', 'b', 'a', 'c'], dtype='object', name='condition') 

print (tmp.index.get_level_values('condition') == 'a') 
[ True False True False] 

print (tmp[tmp.index.get_level_values('condition') == 'a']) 
participant_id condition 
1    a   4 
3    a   1 
dtype: int64 
+0

這也正是它,謝謝。 – Saff