Skip to content

[BUG]: Fix ValueError in concat() when at least one Index has duplicates #36290

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

Merged
merged 16 commits into from
Nov 19, 2020

Conversation

phofl
Copy link
Member

@phofl phofl commented Sep 11, 2020

If obj_labes Index has duplicates and they are not removed from new_labels before redindexing, they are multiplied. So we would get a way too big index.

@jreback jreback added Reshaping Concat, Merge/Join, Stack/Unstack, Explode Bug labels Sep 13, 2020
@jreback jreback added this to the 1.2 milestone Sep 13, 2020
@jreback
Copy link
Contributor

jreback commented Sep 13, 2020

also pls merge master

� Conflicts:
�	doc/source/whatsnew/v1.2.0.rst
�	pandas/tests/reshape/test_concat.py
@phofl
Copy link
Member Author

phofl commented Sep 13, 2020

@jreback merged master

@phofl
Copy link
Member Author

phofl commented Oct 4, 2020

Moved it to algorithms and added a benchmark. I looked through indexing and the with index associated modules but could not find anything, which would help here. The check for uniqueness is not necessary from a technical standpoint, but it should save some time for unique indices.

@github-actions
Copy link
Contributor

github-actions bot commented Nov 4, 2020

This pull request is stale because it has been open for thirty days with no activity. Please update or respond to this comment if you're still interested in working on this.

@github-actions github-actions bot added the Stale label Nov 4, 2020
@simonjayhawkins
Copy link
Member

@phofl can you resolve merge conflicts

� Conflicts:
�	doc/source/whatsnew/v1.2.0.rst
�	pandas/core/algorithms.py
�	pandas/tests/reshape/test_concat.py
@phofl
Copy link
Member Author

phofl commented Nov 12, 2020

Done

# duplicate or duplicates again
if not obj_labels.is_unique:
new_labels = algos.make_duplicates_of_left_unique_in_right(
obj_labels.values, new_labels.values
Copy link
Contributor

Choose a reason for hiding this comment

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

use np.asarray instead of .values

Copy link
Member Author

Choose a reason for hiding this comment

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

Thx, done

@@ -2149,3 +2149,21 @@ def _sort_tuples(values: np.ndarray[tuple]):
arrays, _ = to_arrays(values, None)
indexer = lexsort_indexer(arrays, orders=True)
return values[indexer]


def make_duplicates_of_left_unique_in_right(left, right) -> np.ndarray:
Copy link
Contributor

Choose a reason for hiding this comment

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

can you type the input args.

can you add an example here.

is this unit tested?

Copy link
Member Author

Choose a reason for hiding this comment

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

Added unittests, forgot them obviously, and typed the inputs. Example is below

{"a": [1, 1, 2, 3, np.nan, 4], "b": [6, 7, 8, 8, 9, np.nan]},
index=Index([0, 0, 1, 1, 3, 4]),
)
tm.assert_frame_equal(result, expected)
Copy link
Contributor

Choose a reason for hiding this comment

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

extra file added below

Copy link
Member Author

Choose a reason for hiding this comment

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

Moved the test if that is what you are referring to

@phofl
Copy link
Member Author

phofl commented Nov 13, 2020

Example:

We have the 2 DataFrames

df1 = DataFrame([1, 2, 3, 4], index=[0, 1, 1, 4], columns=["a"])
df2 = DataFrame([6, 7, 8, 9], index=[0, 0, 1, 3], columns=["b"])

When looping over df1 (df2 case is similar)
In this case new_labels before calling make_duplicates_of_left_unique_in_right will be

new_labels=Index([0, 0, 1, 1, 3, 4])

while obj_labels will be

obj_labels=Index([0, 1, 1, 4])

Simply reindexing would return an indexer which would duplicate the pair [1, 1] again: np.array([0, 0, 1, 2, 1, 2, -1, 3]). (taking every 1 twice)
The new function takes the duplications of the 1 in new_labels away.

make_duplicates_of_left_unique_in_right returns

new_labels=Index([0, 0, 1, 3, 4])

which leads us to the desired reindexing result np.array([0, 0, 1, 2, -1, 3])

Copy link
Contributor

@jreback jreback left a comment

Choose a reason for hiding this comment

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

pandas/tests/reshape/test_concat.py seems to be added here (i think we moved this), can you remove; pls merge master and ping on green.

cc @jbrockmendel if comments.

@@ -567,6 +567,7 @@ Reshaping
- Bug in :meth:`DataFrame.combine_first()` caused wrong alignment with dtype ``string`` and one level of ``MultiIndex`` containing only ``NA`` (:issue:`37591`)
- Fixed regression in :func:`merge` on merging DatetimeIndex with empty DataFrame (:issue:`36895`)
- Bug in :meth:`DataFrame.apply` not setting index of return value when ``func`` return type is ``dict`` (:issue:`37544`)
- Bug in :func:`concat` resulted in a ``ValueError`` when at least one of both inputs had a non unique index (:issue:`36263`)
Copy link
Member

Choose a reason for hiding this comment

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

non-unique

Copy link
Member Author

Choose a reason for hiding this comment

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

Done

Duplicates of left are unique in right
"""
left_duplicates = unique(left[duplicated(left)])
return right[~(duplicated(right) & np.isin(right, left_duplicates))]
Copy link
Member

Choose a reason for hiding this comment

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

any reason to prefer np.isin vs the algos.isin?

Copy link
Member Author

Choose a reason for hiding this comment

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

Not that i remember, changed it.

Parameters
----------
left: ndarray
right: ndarray
Copy link
Member

Choose a reason for hiding this comment

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

dtypes unrestricted?

Copy link
Member Author

Choose a reason for hiding this comment

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

Could not think of anything, why they should be restricted.

result = concat([df1, df2], axis=1)
expected = DataFrame(
{"a": [1, 1, 2, 3, np.nan, 4], "b": [6, 7, 8, 8, 9, np.nan]},
index=Index([0, 0, 1, 1, 3, 4]),
Copy link
Member

Choose a reason for hiding this comment

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

just to make sure i understand this, for any df1 and df2, we want result.index to always satisfy:

vc = result.index.value_counts()
vc1 = df1.index.value_counts()
vc2 = df2.index.value_counts()

vc1b = vc1.reindex(vc.index, fill_value=0)
vc2b = vc2.reindex(vc.index, fill_value=0)

We expect vc to be the pointwise maximum of vc1b and vc2b?

Copy link
Member Author

Choose a reason for hiding this comment

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

Yes exactly. Thats perfectly on point.

@@ -2149,3 +2149,23 @@ def _sort_tuples(values: np.ndarray[tuple]):
arrays, _ = to_arrays(values, None)
indexer = lexsort_indexer(arrays, orders=True)
return values[indexer]


def make_duplicates_of_left_unique_in_right(
Copy link
Member

Choose a reason for hiding this comment

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

is this related to or useful for the index.union-with-duplicates stuff?

Copy link
Member Author

Choose a reason for hiding this comment

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

If you pass in the union as left and right, you would get the distinct result. Have to take a look if we can use this.

) -> np.ndarray:
"""
Drops all duplicates values from left in right, so that they are
unique in right.
Copy link
Member

Choose a reason for hiding this comment

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

The code itself looks good, but this sentence isn't clear to a reader without context

Copy link
Member Author

Choose a reason for hiding this comment

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

Improved it?

@phofl
Copy link
Member Author

phofl commented Nov 18, 2020

Removed the test_concat file, probably got in through merging master the last time

@jreback jreback merged commit b32febd into pandas-dev:master Nov 19, 2020
@jreback
Copy link
Contributor

jreback commented Nov 19, 2020

thanks @phofl very nice

@phofl
Copy link
Member Author

phofl commented Nov 19, 2020

Thx, will try to use this for the Index.union with duplicates problems

@phofl phofl deleted the 36263 branch November 19, 2020 19:24
ivirshup added a commit to ivirshup/pandas that referenced this pull request Dec 23, 2020
jreback pushed a commit that referenced this pull request Dec 24, 2020
* Revert "[BUG]: Fix ValueError in concat() when at least one Index has duplicates (#36290)"

This reverts commit b32febd.
@jreback
Copy link
Contributor

jreback commented Dec 24, 2020

reverted here: #38654

luckyvs1 pushed a commit to luckyvs1/pandas that referenced this pull request Jan 20, 2021
* Revert "[BUG]: Fix ValueError in concat() when at least one Index has duplicates (pandas-dev#36290)"

This reverts commit b32febd.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug Reshaping Concat, Merge/Join, Stack/Unstack, Explode
Projects
None yet
Development

Successfully merging this pull request may close these issues.

pd.concat() crashes if dataframe contains duplicate indices but not df.join()
4 participants