字典中循环测试的Scipy

2024-04-20 04:37:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据帧mmLog:

                  Experiment       Logmm
0               Spontaneous1       0.022815
1                     Light1       0.007222
2                       PTZ1       0.03168
3               Spontaneous1       0.015003
4                     Light1       0.013402
5                       PTZ1       0.021539
...                      ...            ...
38072  SpontaneousControl147       0.013685
38073  SpontaneousControl147       0.034702
38074  SpontaneousControl147       0.008993

我想对每个独特的组进行测试,并将其与实验栏中的对照组进行比较。我试图创建一个唯一标识符数据帧的字典

df_uniq = dict()
for k, v in mmLog.groupby('Experiment'):
    df_uniq[k] = v

然后使用for循环

from scipy.stats import ttest_ind

for key in df_uniq: 
    cat1 = key
    cat2 = df[df['Experiment']=='SpontaneousControl147']
    ttest_ind(cat1['Logmm'], cat2['Logmm'])

和get TypeError:字符串索引必须是整数


Tags: 数据keyindfforexperimentinduniq
2条回答

你似乎把事情弄得更复杂了。^{}返回一个^{}对象,该对象具有所需的所有属性,等等。不需要创建多余的自定义词典。你知道吗

例如,从

groups = mmLog.groupby('Experiment')

现在groups.get_group('SpontaneousControl147')将拥有控制组的所有元素:

>>> control = groups.get_group('SpontaneousControl147')['Logmm']
>>> control
38072    0.013685
38073    0.034702
38074    0.008993
Name: Logmm, dtype: float64

或者,您可以使用groups['logmm']只关注您关心的列,它将返回一个SeriesGroupBy对象,您可以从该对象获取控制数据:

control = groups['Logmm'].get_group('SpontaneousControl147')

在这两种情况下,groups支持直接迭代和apply方法。如果不需要汇总结果:

for key, subset in groups:
    if key == 'SpontaneousControl147':
        continue
    ttest(control, subset['Logmm'])

如果要构建Series个ttest值:

groups['Logmm'].apply(lambda data: ttest(control, data))

或者

groups.apply(lambda df: ttest(control, df['Logmm']))

以下是两种TL;DR版本:

  1. 使用完整的DataFrameGroupBy

    groups = mmLog.groupby('Experiment')
    control = groups.get_group('SpontaneousControl147')['Logmm']
    result = groups.apply(lambda df: ttest(control, df['Logmm']))
    
  2. 对感兴趣的列使用SeriesGroupBy

    groups = mmLog.groupby('Experiment')['Logmm']
    control = groups.get_group('SpontaneousControl147')
    result = groups.apply(lamda s: ttest(control, s))
    

要将dict中的值而不是其键赋给cat1

from scipy.stats import ttest_ind

results = {}
for key, val in df_uniq.items(): 
    cat1 = val
    cat2 = df[df['Experiment']=='SpontaneousControl147']
    results[key] = ttest_ind(cat1['Logmm'], cat2['Logmm'])

通过将键分配给cat1,您试图对字符串而不是groupby结果执行T-test。你知道吗

Edit:您还可以从循环中拉出指定cat2的行,因为这只需要执行一次:)

相关问题 更多 >