Skip to content

BUG: Fixed handling of non-list value_vars in melt #15351

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 10 commits into from
2 changes: 2 additions & 0 deletions pandas/core/reshape.py
Original file line number Diff line number Diff line change
Expand Up @@ -771,6 +771,8 @@ def melt(frame, id_vars=None, value_vars=None, var_name=None,
if value_vars is not None:
if not isinstance(value_vars, (tuple, list, 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.

this checking (and in the clause above) should be not is_list_like(value_vars)

value_vars = [value_vars]
else:
value_vars = list(value_vars)
frame = frame.loc[:, id_vars + value_vars]
else:
frame = frame.copy()
Expand Down
14 changes: 14 additions & 0 deletions pandas/tests/test_reshape.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,20 @@ def test_value_vars(self):
columns=['id1', 'id2', 'variable', 'value'])
tm.assert_frame_equal(result4, expected4)

def test_value_vars_types(self):
result_with_tuple = melt(self.df, id_vars=['id1', 'id2'], value_vars=('A', 'B'))
result_with_array = melt(self.df, id_vars=['id1', 'id2'], value_vars=np.array(['A', 'B']))
Copy link
Contributor

Choose a reason for hiding this comment

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

you can do the result checking in a loop, use a list as well


expected = DataFrame({'id1': self.df['id1'].tolist() * 2,
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 add the issue number as a comment

'id2': self.df['id2'].tolist() * 2,
'variable': ['A'] * 10 + ['B'] * 10,
'value': (self.df['A'].tolist() +
self.df['B'].tolist())},
columns=['id1', 'id2', 'variable', 'value'])

tm.assert_frame_equal(result_with_tuple, expected)
tm.assert_frame_equal(result_with_array, expected)

def test_custom_var_name(self):
result5 = melt(self.df, var_name=self.var_name)
self.assertEqual(result5.columns.tolist(), ['var', 'value'])
Expand Down