C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Pandas melt()The Pandas.melt() function is used to unpivot the DataFrame from a wide format to a long format. Its main task is to massage a DataFrame into a format where some columns are identifier variables and remaining columns are considered as measured variables, are unpivoted to the row axis. It leaves just two non-identifier columns, variable and value. Syntaxpandas.melt(frame, id_vars=None, value_vars=None, var_name=None, value_name='value', col_level=None) Parameters
ReturnsIt returns the unpivoted DataFrame as the output. Example# importing pandas as pd import pandas as pd # creating a dataframe info = pd.DataFrame({'Name': {0: 'Parker', 1: 'Smith', 2: 'John'}, 'Language': {0: 'Python', 1: 'Java', 2: 'C++'}, 'Age': {0: 22, 1: 30, 2: 26}}) # Name is id_vars and Course is value_vars pd.melt(info, id_vars =['Name'], value_vars =['Language']) info Output Name Language Age 0 Parker Python 22 1 Smith Java 30 2 John C++ 26 Example2import pandas as pd info = pd.DataFrame({'A': {0: 'p', 1: 'q', 2: 'r'}, 'B': {0: 40, 1: 55, 2: 25}, 'C': {0: 56, 1: 62, 2: 42}}) pd.melt(info, id_vars=['A'], value_vars=['C']) pd.melt(info, id_vars=['A'], value_vars=['B', 'C']) pd.melt(info, id_vars=['A'], value_vars=['C'], var_name='myVarname', value_name='myValname') Output A myVarname myValname 0 p C 56 1 q C 62 2 r C 42
Next TopicDataFrame.merge()
|