Skip to content

ENH: Add optional argument keep_index to dataframe melt method #17459

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
8 changes: 6 additions & 2 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -4367,6 +4367,10 @@ def unstack(self, level=-1, fill_value=None):
Name to use for the 'value' column.
col_level : int or string, optional
If columns are a MultiIndex then use this level to melt.
keep_index : boolean, optional, default False
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 commonly called index=False everywhere else.

add a versionadded

Copy link
Author

Choose a reason for hiding this comment

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

So better to just name it index and if True resulting in the original index with duplicate entries? What about the option @TomAugspurger proposed?

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.

See also
--------
Expand Down Expand Up @@ -4439,11 +4443,11 @@ def unstack(self, level=-1, fill_value=None):
versionadded='.. versionadded:: 0.20.0\n',
other='melt'))
def melt(self, id_vars=None, value_vars=None, var_name=None,
value_name='value', col_level=None):
value_name='value', col_level=None, keep_index=False):
from pandas.core.reshape.reshape import melt
return melt(self, id_vars=id_vars, value_vars=value_vars,
var_name=var_name, value_name=value_name,
col_level=col_level)
col_level=col_level, keep_index=keep_index)

# ----------------------------------------------------------------------
# Time series-related
Expand Down
20 changes: 17 additions & 3 deletions pandas/core/reshape/reshape.py
Original file line number Diff line number Diff line change
Expand Up @@ -720,8 +720,7 @@ def _convert_level_number(level_num, columns):
versionadded="",
other='DataFrame.melt'))
def melt(frame, id_vars=None, value_vars=None, var_name=None,
value_name='value', col_level=None):
# TODO: what about the existing index?
value_name='value', col_level=None, keep_index=False):
if id_vars is not None:
if not is_list_like(id_vars):
id_vars = [id_vars]
Expand Down Expand Up @@ -779,7 +778,22 @@ def melt(frame, id_vars=None, value_vars=None, var_name=None,
mdata[col] = np.asanyarray(frame.columns
._get_level_values(i)).repeat(N)

return DataFrame(mdata, columns=mcolumns)
result = DataFrame(mdata, columns=mcolumns)

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

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 quite awkward, you have several cases which you need to disambiguate. e.g. if the original is a MI or not.

Copy link
Author

Choose a reason for hiding this comment

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

Thanks @jreback for looking over my code and the comment.

I think what I wrote should work with any number of levels.

E. g.

arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
          ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
tuples = list(zip(*arrays))
idx_multi = pd.MultiIndex.from_tuples(tuples)
idx_single = pd.Index(arrays[0])

# Index
print(list(np.tile(idx_single, 1)))
print(list(np.tile(idx_single, 2)))

# MultiIndex
print(list(np.tile(idx_multi, 1)))
print(list(np.tile(idx_multi, 2)))

But do I have to make it more explicit (= Pythonic)? Or did I miss something else?

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] = DataFrame(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