
Sponsored
Sponsored
The pandas library offers a built-in method called melt which can directly transform data frames from wide to long format. This approach is particularly useful and efficient for reshaping data.
Time Complexity: O(n), where n is the number of elements in the DataFrame because the function iterates through each element.
Space Complexity: O(n) as a new DataFrame is created to store the reshaped data.
1import pandas as pd
2
3# Sample DataFrame
4data = {
This solution uses the pandas.melt function to reshape the data from wide to long format. The id_vars parameter is used to identify the columns that should remain steady, while the var_name and value_name specify the names for the new dimension and its corresponding values.
Here, we manually loop through the data, restructuring it by iterating over each record. This method provides a more granular approach compared to using built-in functions.
Time Complexity: O(p * q), where p is the number of products and q is the number of quarters in the data.
Space Complexity: O(n), where n is the total number of elements in the reshaped DataFrame.
1import pandas as pd
2
3# Sample DataFrame
4data = {
5 'product': ['Umbrella', 'SleepingBag'],
6 'quarter_1': [417, 800],
7 'quarter_2': [224, 936],
8 'quarter_3': [379, 93],
9 'quarter_4': [611, 875]
10}
11
12df = pd.DataFrame(data)
13
14# Manual Reshape
15reshaped_data = {'product': [], 'quarter': [], 'sales': []}
16
17for index, row in df.iterrows():
18 for quarter in ['quarter_1', 'quarter_2', 'quarter_3', 'quarter_4']:
19 reshaped_data['product'].append(row['product'])
20 reshaped_data['quarter'].append(quarter)
21 reshaped_data['sales'].append(row[quarter])
22
23reshaped_df = pd.DataFrame(reshaped_data)
24
25print(reshaped_df)This solution constructs a new DataFrame by manually iterating over each entry in the original data. It collects product names, each quarter, and the associated sales figure. Each item is appended to a list that forms the structure of the new DataFrame.