我有一个pandas数据框,其中包含参与者在用户研究期间操作的每个对象的一行。每个参与者都参与了3次研究,每种情况下(a
,b
,c
)各一次,每种情况下约有300-700个对象。
当我报告使用的对象的数量时,我希望确保这不会因条件的不同而有显着差异(我不希望它会这样做,但需要从统计上确认这一点)。
我想我想运行方差分析来比较这3个条件,但我不知道如何获得方差分析所需的数据。
我目前有一些pandas代码来对数据进行分组,并计算每个条件下每个参与者的行数(这样我就可以使用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
为了计算方差分析,我通常只需要通过条件列来过滤它们,例如
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)
然而,由于tmp
是一个Series
而不是我习惯的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'])
我确信这是一个需要解决的简单问题,但如果没有一些帮助,我似乎无法达到目标:)
发布于 2016-09-18 17:29:49
我认为您需要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
如果需要使用Series
,您可以使用条件where select values of Multiindex
by get_level_values
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
https://stackoverflow.com/questions/39560598
复制相似问题