Skip to content

ENH: Add optional argument keep_index to dataframe melt method (merged master onto old PR) #28859

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 3 commits 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
6 changes: 6 additions & 0 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -6312,6 +6312,10 @@ def unstack(self, level=-1, fill_value=None):
Name to use for the 'value' column.
col_level : int or str, optional
If columns are a MultiIndex then use this level to melt.
keep_index : boolean, optional, default False
If True, the original index is reused.
In the resulting MulitIndex the names of the unpivoted columns
are added as an additional level to ensure uniqueness.

Returns
-------
Expand Down Expand Up @@ -6396,6 +6400,7 @@ def melt(
var_name=None,
value_name="value",
col_level=None,
keep_index=False,
):
from pandas.core.reshape.melt import melt

Expand All @@ -6406,6 +6411,7 @@ def melt(
var_name=var_name,
value_name=value_name,
col_level=col_level,
keep_index=keep_index,
)

# ----------------------------------------------------------------------
Expand Down
19 changes: 18 additions & 1 deletion pandas/core/reshape/melt.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ def melt(
var_name=None,
value_name="value",
col_level=None,
keep_index=False,
):
# TODO: what about the existing index?
# If multiindex, gather names of columns on all level for checking presence
Expand Down Expand Up @@ -116,7 +117,23 @@ def melt(
# asanyarray will keep the columns as an Index
mdata[col] = np.asanyarray(frame.columns._get_level_values(i)).repeat(N)

return frame._constructor(mdata, columns=mcolumns)
result = frame._constructor(mdata, columns=mcolumns)

if keep_index:
orig_index_values = list(np.tile(frame.index.get_values(), K))

if len(frame.index.names) == len(set(frame.index.names)):
orig_index_names = frame.index.names
else:
orig_index_names = [
"original_index_{i}".format(i=i) for i in range(len(frame.index.names))
]

result[orig_index_names] = frame._constructor(orig_index_values)

result = result.set_index(orig_index_names + list(var_name))

return result


def lreshape(data, groups, dropna=True, label=None):
Expand Down