Pandas 具有函数的 DataFrame:列变化

Pandas DataFrame with Function: Columns Varying

给定以下 DataFrame:

import pandas as pd
import numpy as np
d=pd.DataFrame({' Label':['a','a','b','b'],'Count1':[10,20,30,40],'Count2':[20,45,10,35],
                'Count3':[40,30,np.nan,22],'Nobs1':[30,30,70,70],'Nobs2':[65,65,45,45],
                'Nobs3':[70,70,22,32]})
d

    Label   Count1  Count2  Count3  Nobs1   Nobs2   Nobs3
0   a           10      20    40.0     30      65      70
1   a           20      45    30.0     30      65      70
2   b           30      10     NaN     70      45      22
3   b           40      35    22.0     70      45      32

我想对每行的每个列组组合(1 和 2、1 和 3、2 和 3)应用 z test for proportions。对于列组,我的意思是,例如 "Count1" 和 "Nobs1".

例如,这样的测试之一是:

count = np.array([10, 20]) #from first row of Count1 and Count2, respectively
nobs = np.array([30, 65]) #from first row of Nobs1 and Nobs2, respectively
pv = proportions_ztest(count=count,nobs=nobs,value=0,alternative='two-sided')[1] #this returns just the p-value, which is of interest
pv
0.80265091465415639

我希望结果 (pv) 进入名为 "p_1_2" 的新列(第一行)或与其各自列相对应的逻辑内容。

总而言之,我面临的挑战如下:

  1. 如何每行应用这个。

  2. ...对于上面提到的每个配对组合。

  3. ...其中 "Count" 和 "Nobs" 列的列名和对数可能会有所不同(假设总会有一个 "Nobs" 列对于每个 "Count" 列)。

与3相关:例如,我可能有一个名为“18-24”的列和另一个名为“18-24_Nobs”的列。

提前致谢!

对于 1) 和 2) 的一项测试,可以对其他测试进行类似编码或在附加循环中进行编码

for i,row in d.iterrows():
    d.loc[i,'test'] = proportions_ztest(count=row['Count1':'Count2'].values,
                                        nobs=row['Nobs1':'Nobs2'].values,
                                        value=0,alternative='two-sided')[1]

对于 3) 应该可以在循环

中用纯 python 处理这些情况