Pandas DataFrame with Function: Columns Varying

Viewed 204

Given the following 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

I would like to apply the z test for proportions on each combination of column groups (1 and 2, 1 and 3, 2 and 3) per row. By column group, I mean, for example, "Count1" and "Nobs1".

For example, one such test would be:

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

I would want the result (pv) to go into a new column (first row) called "p_1_2" or something logical that corresponds to its respective columns.

In summary, here are the challenges I'm facing:

  1. How to apply this per row.

  2. ...for each paired combination, mentioned above.

  3. ...where the column names and number of pairs of "Count" and "Nobs" columns may vary (assuming that there will always be a "Nobs" column for each "Count" column).

Related to 3: For example, I might have a column called "18-24" and another called "18-24_Nobs".

Thanks in advance!

1 Answers
Related