Skip to content

2889. Reshape Data: Pivot

DataFrame weather

Column NameType
cityobject
monthobject
temperatureint

Instructions

  • Write a solution to pivot the data so that each row represents temperatures for a specific month, and each city is a separate column.
  • The result format is in the following example.

Example

Input:

citymonthtemperature
JacksonvilleJanuary13
JacksonvilleFebruary23
JacksonvilleMarch38
JacksonvilleApril5
JacksonvilleMay34
ElPasoJanuary20
ElPasoFebruary6
ElPasoMarch26
ElPasoApril2
ElPasoMay43

Output:

monthElPasoJacksonville
April25
February623
January2013
March2638
May4334

Explanation:

The table is pivoted, each column represents a city, and each row represents a specific month.

Submissions

python
import pandas as pd

def pivotTable(weather: pd.DataFrame) -> pd.DataFrame:
    return weather.pivot(index='month', columns='city', values='temperature')

Explanation

Python (Pandas)
Submitted by @noeyislearning
  • import pandas as pd: This line imports the pandas library and aliases it as pd. Pandas is a popular Python library for data manipulation and analysis.
  • def pivotTable(weather: pd.DataFrame) -> pd.DataFrame:
    • pivotTable is the name of the function.
    • It takes one parameter, weather, which is expected to be a pandas DataFrame (pd.DataFrame). The type hint pd.DataFrame helps developers understand that the function expects a DataFrame object as input.
    • The function is also annotated to return a DataFrame (-> pd.DataFrame).
  • return weather.pivot(index='month', columns='city', values='temperature'):
    • This line uses the pivot method of the DataFrame to transform the weather DataFrame.
    • index='month': This sets the month column of the original DataFrame as the new index (rows) of the resulting pivoted table.
    • columns='city': This argument specifies that the unique values in the city column will become the columns of the resulting DataFrame.
    • values='temperature': This indicates that the values in the temperature column of the original DataFrame will fill the cells of the pivoted table.
    • The result of this operation is a pivoted table where each row represents a month, each column represents a city, and the cell values are the temperatures.