Home >Backend Development >Python Tutorial >How Can I Reshape a Pandas DataFrame from Wide to Long Format Using `pd.melt()`?
This question addresses the need to transform a CSV dataset where date-related information is distributed across multiple columns into a format where each date has its own row. To achieve this transformation, the user employs the pd.melt function.
The original CSV structure resembles:
location name Jan-2010 Feb-2010 March-2010 A "test" 12 20 30 B "foo" 18 20 25
The desired outcome is a table with columns location, name, Date, and Value:
location name Date Value A "test" Jan-2010 12 A "test" Feb-2010 20 A "test" March-2010 30 B "foo" Jan-2010 18 B "foo" Feb-2010 20 B "foo" March-2010 25
The pd.melt function provides the means to restructure the data. It takes several arguments:
df.melt(id_vars=["location", "name"], var_name="Date", value_name="Value")
The resulting DataFrame matches the desired output, with each month now occupying a separate row.
The above is the detailed content of How Can I Reshape a Pandas DataFrame from Wide to Long Format Using `pd.melt()`?. For more information, please follow other related articles on the PHP Chinese website!