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.
1#include <vector>
2#include <map>
3#include <string>
4using namespace std;
5
vector<map<string, int>> reformatDepartmentTable(vector<map<string, int>> department) {
map<int, map<string, int>> resultMap;
vector<string> months = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
// Aggregate by id and fill revenue for each month
for (auto &row : department) {
int id = row["id"];
int revenue = row["revenue"];
string month = row["month"];
resultMap[id][month + "_Revenue"] = revenue;
}
// Construct the result
vector<map<string, int>> reformattedData;
for (auto &[id, revenues] : resultMap) {
map<string, int> data;
data["id"] = id;
for (const string &month : months) {
data[month + "_Revenue"] = revenues[month + "_Revenue"];
}
reformattedData.push_back(data);
}
return reformattedData;
}
This C++ solution uses nested maps to aggregate the data. It first creates a mapping from department ids to their corresponding month revenue data. Then, it iterates over all departments to build the final result, handling the absence of revenue data with default values.