Skip to main content
 首页 » 编程设计

python之具有函数 : Columns Varying 的 Pandas DataFrame

2024年10月01日8lyhabc

给定以下 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 

我想申请 z test for proportions在每行的每个列组组合(1 和 2、1 和 3、2 和 3)上。对于列组,我的意思是,例如,“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”列的列名称和成对数量可能不同(假设每个“Count”列始终有一个“Nobs”列)。

与 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 处理这些情况