-
-
Notifications
You must be signed in to change notification settings - Fork 18.5k
Simultaneously melt multiple columns #17676
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
Comments
Its showing me following error when I am using - list of lists in value_vars: |
the example with fruits and drinks is throwing an |
One efficient option for simultaneously melting multiple columns is pivot_longer from pyjanitor ... it offers a variety of options for transforming to long form; for this particular use case, simply pass a list of regular expressions that match the columns to be melted :
Solution to the first example: (df
.pivot_longer(
index = ['City', 'State'],
column_names = slice('Mango', 'Vodka'),
names_to = ('Fruit', 'Drink'),
values_to = ['Pounds', 'Ounces'],
names_pattern = ['M|O|W', 'G|V'])
)
City State Fruit Pounds Drink Ounces
0 Houston Texas Mango 4 Gin 16.0
1 Austin Texas Mango 10 Gin 200.0
2 Hoover Alabama Mango 90 Gin 34.0
3 Houston Texas Orange 10 Vodka 20.0
4 Austin Texas Orange 8 Vodka 33.0
5 Hoover Alabama Orange 14 Vodka 18.0
6 Houston Texas Watermelon 40 NaN NaN
7 Austin Texas Watermelon 99 NaN NaN
8 Hoover Alabama Watermelon 43 NaN NaN Solution to the second example: (df1
.pivot_longer(
index = 'group',
names_to = ('variable_exp', 'variable_res'),
values_to = ('exp', 'res'),
names_pattern = ('exp', 'res'))
.assign(
variable_exp = lambda df: df.variable_exp.str[-1],
variable_res = lambda df: df.variable_res.str[-1])
)
group variable_exp exp variable_res res
0 a 1 4 1 8
1 b 1 10 1 5
2 c 1 -9 1 4
3 a 2 10 3 11
4 b 2 8 3 0
5 c 2 14 3 7 You can view the source_code, specifically from line 815. |
Melt Enhancement
Summary: This is a proposal with a pull request to enhance
melt
to simultaneously melt multiple groups of columns and to add functionality fromwide_to_long
along with better MultiIndexing capabilities. See this notebook for more examples.value_vars
. Each group gets melted into its own column. This feature replaces the need for lreshape.stubnames
(boolean),prefix
andsep
from functionwide_to_long
. It keeps the suffixes in separate columns and does not align them in the same way.melt
, slightly slower thanlreshape
and much faster thanwide_to_long
Use a list of lists in
value_vars
to melt the fruit and drinkswide_to_long
functionality. Added parametersstubnames
(boolean),sep
andsuffix
.Also adds support for all kinds of multiindexing
Problem description
Currently, there is poor support for simultaneous melting of multiple groups of columns.
lreshape
is old and undocumented.wide_to_long
api does not matchmelt
and it's slow.The text was updated successfully, but these errors were encountered: