8000 BUG: Avoid duplicating entire exploded column when joining back with origi… by MarcoGorelli · Pull Request #28010 · pandas-dev/pandas · GitHub
[go: up one dir, main page]

Skip to content

BUG: Avoid duplicating entire exploded column when joining back with origi… #28010

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 23 commits into from
Sep 17, 2019
Merged
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Avoid having to keep track of index names
  • Loading branch information
Marco Gorelli authored and MarcoGorelli committed Sep 3, 2019
commit dc80a946abb35fdfdfe0dfa9349ed45989877346
19 changes: 8 additions & 11 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -6259,28 +6259,25 @@ def explode(self, column: Union[str, Tuple]) -> "DataFrame":
if not self.columns.is_unique:
raise ValueError("columns must be unique")

if isinstance(self.index, MultiIndex):
index_names = [
"level_{num}".format(num=num) if val is None else val
for num, val in enumerate(self.index.names)
]
else:
index_names = [i if i else "index" for i in [self.index.name]]
named_index = any(i for i in self.index.names)

column_with_index = self[column].reset_index()

result = (
self.drop([column], axis=1)
.reset_index()
.join(column_with_index[column].explode())
.set_index(index_names)
.reindex(columns=self.columns, copy=False)
)

if isinstance(self.index, MultiIndex):
result.index.names = self.index.names
result.index = pandas.MultiIndex.from_frame(result.iloc[:, :self.index.nlevels])
else:
result.index.name = self.index.name
result.index = result.iloc[:, 0]

if not named_index:
result.index.names = [None]*self.index.nlevels

result = result.reindex(columns=self.columns, copy=False)

return result

Expand Down
0