Skip to content

suggestion for CompareMeans when passing DataFrame #5479

Open

Description

@stevenlis

I was exposed to using .from_data() classmethod to return a CompareMeans object in #4774 .

The example @adrienpacifico provided:

import pandas as pd
import statsmodels.stats

df1 = pd.DataFrame({"Age": [21,23,54], 'Income': [200, 150,600]})
df2 = pd.DataFrame({"Age": [30,26,34], 'Income': [400, 250,100]})

print(statsmodels.stats.weightstats.CompareMeans.from_data(df1,df2).summary())

Output

                          Test for equality of means                          
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
subset #1      2.6667     10.929      0.244      0.819     -27.677      33.011
subset #2     66.6667    166.667      0.400      0.710    -396.074     529.408
==============================================================================

Instead of the column name issue mentioned by @josef-pkt. I would strongly suggest to rethink of the input dtype of this classmethod. By all means, unlike numpy array, passing two DataFrame could be very confusing due to the existence of column name, which gives meanings to the underlying data.

I could literately change the name of the columns in both dataframe to whatever I want and then get the exact same result.

import pandas as pd
import statsmodels.stats.api as sms

df1 = pd.DataFrame({'a': [21,23,54], 'b': [200, 150,600]})
df2 = pd.DataFrame({'c': [30,26,34], 'd': [400, 250,100]})
print(sms.CompareMeans.from_data(df1, df2).summary())

# Test for equality of means                          
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
subset #1      2.6667     10.929      0.244      0.819     -27.677      33.011
subset #2     66.6667    166.667      0.400      0.710    -396.074     529.408
==============================================================================

The output will vary if I change the postion of the columns in the dataframe like the following:

df1 = pd.DataFrame({'a': [21,23,54], 'b': [200, 150,600]})
df2 = pd.DataFrame({'d': [400, 250,100], 'c': [30,26,34]})
print(sms.CompareMeans.from_data(df1, df2).summary())

# Test for equality of means                          
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
subset #1   -217.3333     87.259     -2.491      0.067    -459.603      24.936
subset #2    286.6667    142.419      2.013      0.114    -108.751     682.085
==============================================================================

However, before and after the change, there is no difference of the data stored in df2. I would say both of the outputs are meaningless since we don't know what the connection between those two dataframe is. In the real word, we mainly dealing with dataframe in a tidy format. I think StatsModels as a statistical analysis package shouldn't worry about this formatting issue like column names but require its users to do any necessary data tidying before using it. The above two dataframe should be merged as df like the following with a new column to idenfy group informaion.

image

And then use .loc to index data and pass them to sms.CompareMeans()

group1 = df.loc[df.Group == 'group1', 'Age']
group2 = df.loc[df.Group == 'group2', 'Age']
cm = sms.CompareMeans.from_data(group1, group2)
print(cm.summary())

# Test for equality of means                          
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
subset #1      2.6667     10.929      0.244      0.819     -27.677      33.011
==============================================================================

I wish there could be a function that could automatically return the summary for both Age and Income columns. I can simply pass the name of the dataframe, list of columns storing data, and the column with group label.

Activity

  1. stevenlis commented on Jan 28, 2019

    @stevenlis
    Author

    I think it could be something like this:

    import pandas as pd
    import statsmodels.stats.api as sms
    from IPython.display import display
    
    def cm_from_df(df, test_list, groups):
    
        '''performing CompareMeans() for multiple columns in a dataframe
    
        Args:
            df (dataframe):
                the dataframe that stores data
            groups (str):
                the column name in the dataframe storing group label
            test_list (list):
                the list of column name storing values that being tested
    
        Raises:
            ValueError('Function can only be applied to two groups')
    
        Returns:
            display dataframe storing summary from CompareMeans()
    
        '''
    
        if df[groups].nunique() == 2:
            # extracting two groups name
            str_group1 = df[groups].unique()[0]
            str_group2 = df[groups].unique()[1]
            # extracting groups data for each col in test_list
            summary_df_all = pd.DataFrame([])
            for col in test_list:
                group1 = df.loc[df[groups] == str_group1, col].dropna()
                group2 = df.loc[df[groups] == str_group2, col].dropna()
                # getting summary
                dsw_group1 = sms.DescrStatsW(group1)
                dsw_group2 = sms.DescrStatsW(group2)
                cm = sms.CompareMeans(dsw_group1, dsw_group2)
                # extracting data from summary
                summary = cm.summary().data[1][1:]
                summary = [float(i) for i in summary]
                coef = summary[0]
                std_err = summary[1]
                t_statistic = summary[2]
                p_value = summary[3]
                ci = [[(summary[-2]), summary[-1]]]
                # test results dataframe
                data = {'coef': coef, 'std err': std_err ,
                        't': t_statistic, 'P>|t|': p_value,
                        '[95% CI]': ci}
                summary_df = pd.DataFrame(data=data, index=[col])
                summary_df_all = summary_df_all.append(summary_df)
            # display output
            title = f'summary of {groups}: {str_group1}/{str_group2}'
            display(title, summary_df_all)
    
        else:
            raise ValueError('Function can only be applied to two groups')

    seaborn has a tips sample dataframe:

    import seaborn as sns
    df = sns.load_dataset('tips')
    df.head()

    image

    Test the function with this dataframe:

    test_list = ['total_bill', 'tip', 'size']
    # sex group
    cm_from_df(df=df, test_list=test_list, groups='sex')
    # smoker group
    cm_from_df(df=df, test_list=test_list, groups='smoker')

    output:
    image

    cm_from_df.zip

  2. josef-pkt commented on Jan 28, 2019

    @josef-pkt
    Member

    I have not looked at all the details of your comment yet.

    The case that this handles would be useful to support, but more likely not as replacement but in addition to the current function.

    The usecase I have in mind does not necessarily have matching column names, e.g. all against one

    df1 = df['control']
    df2 = df[['treatment_1', treatment_2', ... 'treatment_k']]
    

    or flattened multi-indices, e.g.
    df1 = all variables that startwith('West')
    df1 = all variables that startwith('East')

    But I wrote those with numpy cases in mind, and the pandas version just replicates.

    My guess is that a simple 2-way comparison as in your last example might just be something like (I'm not sure I'm using pandas correctly

    df_endog = df(['total_bill', 'tip', 'size'])
    df1 = df_endog[df['Sex'] == 'Male']
    df2 = df_endog[df['Sex'] == 'Female']
    

    specifying the comparison variables directly is getting much closer to a model and formula interface, e.g.
    'total_bill + tip + size ~ Sex'
    which requires data in long form, and would be similar to OLS with a mutlivariate/vectorized response variable endog.
    Once we are in that setting, there is also no restriction to 2 sample comparison, i.e. non-binary categorical variables and interaction effects are available.

    Thanks for the feedback and the suggestion. API design in statsmodels.stats is difficult, and seeing other usecases or proposals for API are very helpful.

    my main conclusion right now is that:
    The current interface is useful because the column name agnostic handling of dataframes provides more flexibility as long as the user puts the right columns.
    However, it would be easier for users to have (also) a more explicit interface that is not name agnostic to handle commmon special cases.

  3. stevenlis commented on Jan 29, 2019

    @stevenlis
    Author

    Thanks for the additional information to help me understand this. I do agree with you, and there is always be a case where you may need the current interface. What you said also reflects my frustration with the current API. For example, there're three ways to get a CompareMeans object. For a t-test, SM has functions and methods. For different types of the t-test, it has different functions. But I think it might be more user-friendly to have a single function and then pass an argument to indicate the type of t-test. I can also see multiple interfaces to get the results of the Tukey HSD test. I just feel they are all over the place and it is a little bit hard to understand the structure of the API. Plus, the functions take all different kind of dtype inputs.

    I think we may need to think about the role of SM in the Python community as well as in a data analysis workflow.

    In the Python community, clearly, using other packages like pandas to tidy data is not an issue. As a result, requiring users to have a tidy dataframe should be a burden. In addition, for numpy array, there is already some low-level packages like scipy.stats. Thus, in my opinion, SM should serve as a high-level interface for data analysis. I saw the relationship between scipy.stats and SM is like matplotlib and seaborn.

    In a data analysis workflow, we often need both descriptive statistics and inferential statistics. In fact, many examples of inferential statistics in the doc are df based. If all functions in SM assume a single dtype of input, it will make SM easier to understand and use, and we can have a more smooth workflow that focuses on statistics.

    Given the current stage of SM, it indeed would be hard to redesign all the interfaces based on DataFrame. Btw, thanks for this fantastic package that makes statistical analysis with Python possible.
    👍

  4. josef-pkt commented on Jan 29, 2019

    @josef-pkt
    Member

    I saw the relationship between scipy.stats and SM is like matplotlib and seaborn.

    That's mostly not the same pattern. statsmodels and scipy.stats are much more in parallel where we have mainly the scipy.stats distributions that are heavily used in statsmodels. Although we have an issue to provide wrappers for scipy.stats functions that directly support pandas.
    statsmodels has to implement both high level and low levels of statistics and econometrics (but in most cases not the even lower level numerical tools that we get from scipy optimize, linalg, special and so on.)

    The main problem I or we have in the API design for statsmodels and specifically statsmodels.stats is that there are many different use cases, and many of those are not using pandas.

    A few items or thoughts:

    I'm still mostly a numpython person and still a bit skeptical about the usage of pandas inside a library. For most parts we still follow the pattern to have pandas support from and on the outside but only numpy on the inside.

    Not all of our users or usage is oriented towards data science and pandas data handling. We, and scipy, still have a large user group in science and engineering that don't always use pandas. We also have statsmodels for library use, that might use pandas for some parts but not all. Many stats functions are also for library use in the rest of statsmodels, and there we handle pandas support separately.

    Different use cases even withing the same user. From my own experience, I have two cases, sometimes I just want to quickly use a function and look at the main result and I don't care about any details. In other cases I really want to look carefully at many related statistics and details for a specific case.
    In the former case, I prefer a simple function that just gives me a final number (e.g. I like quick confidence intervals for proportions when I run a Monte Carlo simulation). In the latter case, I want a class that provides as much information as possible, having everything together and easily accessible without duplicating computations.
    That was the motivation behind providing shortcut functions and a full class, for example, for t_tests.

    So for now, I'm generally in favor of adding more APIs and functionality that targets different use cases (and possibly having different implementations of the same functionality) because I'm not sure about what design would satisfy those different requirements.

  5. stevenlis commented on Jan 29, 2019

    @stevenlis
    Author

    So for now, I'm generally in favor of adding more APIs and functionality that targets different use cases (and possibly having different implementations of the same functionality) because I'm not sure about what design would satisfy those different requirements.

    Maybe just a few top-level functions to return objects for each type of test and then all the details you need can be accessed via class methods. For example, the following three ways to get CompareMeans object can simply be cut to one way since the original input dtype is just numpy array. Simplicity is beauty right? Is that why we all love Python..Anyway.. (Btw, I'm actually a more social science person with an economics background)

    import numpy as np
    from scipy import stats
    import statsmodels.stats.api as sms
    # two groups of data:
    mean, std, size = 2, 3, 100
    d1 = np.random.normal(mean, std, size)
    mean, std, size = 10, 4, 100
    d2 = np.random.normal(mean, std, size)
    # return DescrStatsW object
    dsw_d1 = sms.DescrStatsW(d1)
    dsw_d2 = sms.DescrStatsW(d2)
    
    # using .CompareMeans() function:
    cm1 = sms.CompareMeans(dsw_d1, dsw_d2)
    
    # using .from_data() method:
    cm2 = sms.CompareMeans.from_data(d1, d2)
    
    # using .get_compare() method:
    cm3 = dsw_d1.get_compare(dsw_d2)
    
    # results:
    print(cm1.summary())
    print(cm2.summary())
    print(cm3.summary())
  6. added this to the 0.11 milestone on Feb 3, 2019
  7. modified the milestones: 0.11, josef on Oct 5, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions