Sponsored
Sponsored
This approach involves using a pivot table strategy to reformat the data. The key is to transform row data of each month's revenue into separate columns for each month. We will iterate through the table, grouping revenues by department id and arranging them into columns corresponding to each month.
Time Complexity: O(n), where n is the number of rows in the input table.
Space Complexity: O(n), for storing the pivoted DataFrame.
1import pandas as pd
2
3def reformat_department_table(df):
4 # Pivot the table with id as index and month as columns
5 pivot_df = df.pivot(index='id', columns='month', values='revenue')
6 # Rename columns to include '_Revenue'
7 pivot_df.columns = [f'{month}_Revenue' for month in pivot_df.columns]
8 return pivot_df.reset_index().to_dict(orient='records')
This solution leverages pandas to pivot the DataFrame. The pivot operation uses the 'id' as index and 'month' as columns, transforming the revenue data into month-column format. Finally, the columns are renamed to include the '_Revenue' suffix, and the result is returned in dictionary format.
This approach focuses on iterating over the data, storing information using an aggregation map or dictionary. Each department will have its own dictionary that maps months to revenue, allowing us to easily access and format this data into the desired output structure.
Time Complexity: O(n * m), where n is the number of departments and m is the number of months.
Space Complexity: O(n * m), with m fixed at 12, for storing department-month mappings.
1import java.util.*;
2
3
This Java solution uses a HashMap to collect month-specific revenue data for each department. After populating this map, it constructs the output list by iterating over departments, ensuring that all months are represented, inserting null where revenue data is absent.