Prepin
Log in

Develop a function that takes structured data, including column names, as input and produces the data in a format suitable for creating a pivot table.

Approach / Explanation

This question essentially requires you to showcase your capability to develop a function that accepts structured data as input, which will include column names. The function should be crafted so that its output is formatted appropriately for direct use in creating a Pivot Table. Important aspects to consider when answering this question include: Grasping the structure of the data, including its column names. Knowing how to manipulate the data in an organized manner. Comprehending the structure necessary for generating a Pivot Table. Being able to apply this understanding in a function that produces the required structure from the input data.

Suggested Answer

You can define a function in Python utilizing the pandas library that accepts a DataFrame as input and reformats it for use in a pivot table. Here’s a straightforward example: import pandas as pd def pivot_table_ready ( df ) : # Re-format the data frame so it's suitable for a pivot table df_pivot_ready = df . melt ( id_vars = 'column_name' , value_vars = df . columns ) return df_pivot_ready In this function, be sure to substitute column_name with the specific column you wish to use as the basis for your pivot table. The line value_vars=df.columns instructs pandas to treat all columns except column_name as value variables.

Alternative Answer

If the data structure is intricate, it may necessitate more sophisticated handling. Below is an illustration of how the function could be structured: import pandas as pd def pivot_table_ready ( df , index_column ) : # Adjust the data frame format for pivot table suitability value_columns = [ col for col in df . columns if col != index_column ] df_pivot_ready = df . melt ( id_vars = index_column , var_name = 'Column' , value_vars = value_columns , value_name = 'Value' ) return df_pivot_ready In this function, the index_column parameter allows you to specify the index for the pivot table. This function thus offers a more versatile solution, capable of accommodating datasets with uncertain or varying formats. The names 'Column' and 'Value' are assigned to the var_name and value_name parameters respectively, enhancing the clarity of the dataframe and simplifying the creation of Pivot tables.

Question Details

Difficulty & Category

Medium
technical

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.