Repository navigation
Description
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.
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
stevenlis commentedon Jan 28, 2019
I think it could be something like this:
seabornhas atipssample dataframe:Test the function with this dataframe:
output:

cm_from_df.zip
josef-pkt commentedon Jan 28, 2019
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
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
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.
stevenlis commentedon Jan 29, 2019
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
CompareMeansobject. For a t-test,SMhas 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
SMin the Python community as well as in a data analysis workflow.In the Python community, clearly, using other packages like
pandasto tidy data is not an issue. As a result, requiring users to have a tidy dataframe should be a burden. In addition, fornumpyarray, there is already some low-level packages likescipy.stats. Thus, in my opinion,SMshould serve as a high-level interface for data analysis. I saw the relationship betweenscipy.statsandSMis likematplotlibandseaborn.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
dfbased. If all functions inSMassume a single dtype of input, it will makeSMeasier 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 onDataFrame. Btw, thanks for this fantastic package that makes statistical analysis with Python possible.👍
josef-pkt commentedon Jan 29, 2019
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.
stevenlis commentedon Jan 29, 2019
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
CompareMeansobject 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)