Skip to content

ENH: Add axis argument to Dataframe.corr #35984

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 17 commits into from
Closed
Show file tree
Hide file tree
Changes from 8 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
20 changes: 17 additions & 3 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -8116,9 +8116,9 @@ def _series_round(s, decimals):
# ----------------------------------------------------------------------
# Statistical methods, etc.

def corr(self, method="pearson", min_periods=1) -> "DataFrame":
def corr(self, method="pearson", min_periods=1, axis=0) -> "DataFrame":
"""
Compute pairwise correlation of columns, excluding NA/null values.
Compute pairwise correlation of rows or columns, excluding NA/null values.

Parameters
----------
Expand All @@ -8140,6 +8140,10 @@ def corr(self, method="pearson", min_periods=1) -> "DataFrame":
to have a valid result. Currently only available for Pearson
and Spearman correlation.

axis : {0 or 'index', 1 or 'columns'}, default 0
The axis to use. 0 or 'index' to compute column-wise, 1 or 'columns' for
row-wise.

Returns
-------
DataFrame
Expand All @@ -8162,12 +8166,22 @@ def corr(self, method="pearson", min_periods=1) -> "DataFrame":
dogs cats
dogs 1.0 0.3
cats 0.3 1.0
>>> df.corr(method=histogram_intersection, axis=1)
Copy link
Contributor

Choose a reason for hiding this comment

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

blank line before

Copy link
Contributor

Choose a reason for hiding this comment

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

add a comment as well

0 1 2 3
0 1.0 0.3 0.2 0.3
1 0.3 1.0 0.0 0.1
2 0.2 0.0 1.0 0.2
3 0.3 0.1 0.2 1.0
"""
numeric_df = self._get_numeric_data()
cols = numeric_df.columns
axis = numeric_df._get_axis_number(axis)
cols = numeric_df._get_agg_axis(axis)
idx = cols.copy()
mat = numeric_df.to_numpy(dtype=float, na_value=np.nan, copy=False)

if axis == 1:
Copy link
Contributor

Choose a reason for hiding this comment

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

don't we have to transpose the results?

Copy link
Member

Choose a reason for hiding this comment

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

I don't think we do since the result is symmetric

mat = mat.transpose()

if method == "pearson":
correl = libalgos.nancorr(mat, minp=min_periods)
elif method == "spearman":
Expand Down
9 changes: 9 additions & 0 deletions pandas/tests/frame/methods/test_cov_corr.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,15 @@ def test_corr_int(self):
df3.cov()
df3.corr()

@td.skip_if_no_scipy
@pytest.mark.parametrize("meth", ["pearson", "spearman"])
def test_corr_axes(self, meth):
# https://github.com/pandas-dev/pandas/issues/35002
df = pd.DataFrame(np.random.normal(size=(10, 2)))
expected = df.T.corr(meth, axis=0)
Copy link
Member

Choose a reason for hiding this comment

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

I think it's usually encouraged to explicitly write out the expected DataFrame so that expected doesn't go down the same code path as result

Copy link
Author

Choose a reason for hiding this comment

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

Yeah I could do that but, wouldn't it just be a test for Dataframe.corr function itself. Since the original operations to be done on matrix itself are left unchanged.

Personally I don't think explicitly writing Dataframe in this case is needed, unless (as you suggested) instead of taking a transpose we implement a workaround involving changing the main function itself.

Copy link
Member

Choose a reason for hiding this comment

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

OK sure, perhaps wait for others' comments then

Copy link
Member

Choose a reason for hiding this comment

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

The test comes close to being circular but I think it's probably okay here. In this case it's hard to explicitly construct the expected DataFrame for all methods "from scratch" without either trivial input data or messy juggling of different scipy functions.

result = df.corr(meth, axis=1)
tm.assert_frame_equal(result, expected)

@td.skip_if_no_scipy
@pytest.mark.parametrize(
"nullable_column", [pd.array([1, 2, 3]), pd.array([1, 2, None])]
Expand Down