Skip to content

ENH: Allow parameters method and min_periods in DataFrame.corrwith() #15573

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/computation.rst
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,7 @@ objects.
df2 = pd.DataFrame(np.random.randn(4, 4), index=index[:4], columns=columns)
df1.corrwith(df2)
df2.corrwith(df1, axis=1)
df2.corrwith(df1, axis=1, method='kendall')
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add versionsddes tag (and small comment here)


.. _computation.ranking:

Expand Down
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.20.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,7 @@ Other enhancements
- ``pd.TimedeltaIndex`` now has a custom datetick formatter specifically designed for nanosecond level precision (:issue:`8711`)
- ``pd.types.concat.union_categoricals`` gained the ``ignore_ordered`` argument to allow ignoring the ordered attribute of unioned categoricals (:issue:`13410`). See the :ref:`categorical union docs <categorical.union>` for more information.
- ``pandas.io.json.json_normalize()`` with an empty ``list`` will return an empty ``DataFrame`` (:issue:`15534`)
- ``pd.DataFrame.corrwith()`` now accepts ``method`` and ``min_periods`` as optional arguments, as in pd.DataFrame.corr() and pd.Series.corr() (:issue:`9490`)

.. _ISO 8601 duration: https://en.wikipedia.org/wiki/ISO_8601#Durations

Expand Down
34 changes: 20 additions & 14 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -4819,7 +4819,8 @@ def cov(self, min_periods=None):

return self._constructor(baseCov, index=idx, columns=cols)

def corrwith(self, other, axis=0, drop=False):
def corrwith(self, other, axis=0, drop=False, method='pearson',
min_periods=1):
"""
Compute pairwise correlation between rows or columns of two DataFrame
objects.
Expand All @@ -4831,36 +4832,41 @@ def corrwith(self, other, axis=0, drop=False):
0 or 'index' to compute column-wise, 1 or 'columns' for row-wise
drop : boolean, default False
Drop missing indices from result, default returns union of all
method : {'pearson', 'kendall', 'spearman'}
* pearson : standard correlation coefficient
* kendall : Kendall Tau correlation coefficient
* spearman : Spearman rank correlation

.. versionadded:: 0.20.0

min_periods : int, optional
Minimum number of observations needed to have a valid result

.. versionadded:: 0.20.0

Returns
-------
correls : Series
"""
axis = self._get_axis_number(axis)
if isinstance(other, Series):
return self.apply(other.corr, axis=axis)
return self.apply(other.corr, axis=axis,
method=method, min_periods=min_periods)

this = self._get_numeric_data()
other = other._get_numeric_data()

left, right = this.align(other, join='inner', copy=False)

# mask missing values
left = left + right * 0
right = right + left * 0

if axis == 1:
left = left.T
right = right.T

# demeaned data
ldem = left - left.mean()
rdem = right - right.mean()

num = (ldem * rdem).sum()
dom = (left.count() - 1) * left.std() * right.std()

correl = num / dom
correl = Series({col: nanops.nancorr(left[col].values,
right[col].values,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is going to be very slow

we need to rework nancorr to do this instead

Copy link
Author

@anthonyho anthonyho Mar 5, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the new implementation (which calls nancorr which in turns calls numpy/scipy correlation functions) is actually significantly faster than the current implementation (manually computing Pearson correlation using DataFrame.mean(), DataFrame.sum(), and DataFrame.std())

For example:

Current implementation:

>>> import pandas as pd; import timeit
>>> pd.__version__
u'0.19.2'
>>> iris = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv')
>>> timeit.timeit(lambda: iris.corrwith(iris), number=10000)
50.891642808914185
>>> timeit.timeit(lambda: iris.T.corrwith(iris.T), number=10000)
42.0677649974823

New implementation:

>>> import pandas as pd; import timeit
>>> pd.__version__
'0.19.0+539.g0b77680.dirty'
>>> iris = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv')
>>> timeit.timeit(lambda: iris.corrwith(iris, method='pearson'), number=10000)
28.622286081314087
>>> timeit.timeit(lambda: iris.T.corrwith(iris.T, method='pearson'), number=10000)
21.898916959762573

I'm pretty new to this, so please let me know if I'm missing anything here.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

look thru the benchmarks and pls add some asv as appropriate

include wide and talk data

on wide data this will be slower

method=method,
min_periods=min_periods)
for col in left.columns})

if not drop:
raxis = 1 if axis == 0 else 0
Expand Down
70 changes: 39 additions & 31 deletions pandas/tests/frame/test_analytics.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,28 +181,33 @@ def test_corrwith(self):
b = b.reindex(columns=b.columns[::-1], index=b.index[::-1][10:])
del b['B']

colcorr = a.corrwith(b, axis=0)
tm.assert_almost_equal(colcorr['A'], a['A'].corr(b['A']))

rowcorr = a.corrwith(b, axis=1)
tm.assert_series_equal(rowcorr, a.T.corrwith(b.T, axis=0))

dropped = a.corrwith(b, axis=0, drop=True)
tm.assert_almost_equal(dropped['A'], a['A'].corr(b['A']))
self.assertNotIn('B', dropped)

dropped = a.corrwith(b, axis=1, drop=True)
self.assertNotIn(a.index[-1], dropped.index)

# non time-series data
index = ['a', 'b', 'c', 'd', 'e']
columns = ['one', 'two', 'three', 'four']
df1 = DataFrame(randn(5, 4), index=index, columns=columns)
df2 = DataFrame(randn(4, 4), index=index[:4], columns=columns)
correls = df1.corrwith(df2, axis=1)
for row in index[:4]:
tm.assert_almost_equal(correls[row],
df1.loc[row].corr(df2.loc[row]))
for meth in ['pearson', 'kendall', 'spearman']:
colcorr = a.corrwith(b, axis=0, method=meth)
tm.assert_almost_equal(colcorr['A'],
a['A'].corr(b['A'], method=meth))

rowcorr = a.corrwith(b, axis=1, method=meth)
tm.assert_series_equal(rowcorr,
a.T.corrwith(b.T, axis=0, method=meth))

dropped = a.corrwith(b, axis=0, drop=True, method=meth)
tm.assert_almost_equal(dropped['A'],
a['A'].corr(b['A'], method=meth))
self.assertNotIn('B', dropped)

dropped = a.corrwith(b, axis=1, drop=True, method=meth)
self.assertNotIn(a.index[-1], dropped.index)

# non time-series data
index = ['a', 'b', 'c', 'd', 'e']
columns = ['one', 'two', 'three', 'four']
df1 = DataFrame(randn(5, 4), index=index, columns=columns)
df2 = DataFrame(randn(4, 4), index=index[:4], columns=columns)
correls = df1.corrwith(df2, axis=1, method=meth)
for row in index[:4]:
tm.assert_almost_equal(correls[row],
df1.loc[row].corr(df2.loc[row],
method=meth))

def test_corrwith_with_objects(self):
df1 = tm.makeTimeDataFrame()
Expand All @@ -212,19 +217,22 @@ def test_corrwith_with_objects(self):
df1['obj'] = 'foo'
df2['obj'] = 'bar'

result = df1.corrwith(df2)
expected = df1.loc[:, cols].corrwith(df2.loc[:, cols])
tm.assert_series_equal(result, expected)
for meth in ['pearson', 'kendall', 'spearman']:
result = df1.corrwith(df2, method=meth)
expected = df1.loc[:, cols].corrwith(df2.loc[:, cols], method=meth)
tm.assert_series_equal(result, expected)

result = df1.corrwith(df2, axis=1)
expected = df1.loc[:, cols].corrwith(df2.loc[:, cols], axis=1)
tm.assert_series_equal(result, expected)
result = df1.corrwith(df2, axis=1, method=meth)
expected = df1.loc[:, cols].corrwith(df2.loc[:, cols],
axis=1, method=meth)
tm.assert_series_equal(result, expected)

def test_corrwith_series(self):
result = self.tsframe.corrwith(self.tsframe['A'])
expected = self.tsframe.apply(self.tsframe['A'].corr)
for meth in ['pearson', 'kendall', 'spearman']:
result = self.tsframe.corrwith(self.tsframe['A'], method=meth)
expected = self.tsframe.apply(self.tsframe['A'].corr, method=meth)

tm.assert_series_equal(result, expected)
tm.assert_series_equal(result, expected)

def test_corrwith_matches_corrcoef(self):
df1 = DataFrame(np.arange(10000), columns=['a'])
Expand Down