How does the pivot function rearrange the data?

0245

The pivot function in pandas rearranges data by transforming or reshaping a DataFrame from a long format to a wide format. It allows you to specify which columns to use as the new index, columns, and values in the resulting DataFrame.

Here's how it works:

  1. Index: You specify which column(s) should become the new index (row labels) of the DataFrame.
  2. Columns: You specify which column should be used to create new columns in the resulting DataFrame.
  3. Values: You specify which column's values should fill the cells of the new DataFrame.

Example

Suppose you have the following long format DataFrame:

Date Location Value
2023-01-01 A 10
2023-01-01 B 20
2023-01-02 A 15
2023-01-02 B 25

You can use the pivot function to rearrange this data:

import pandas as pd

# Sample DataFrame
data = {
    'Date': ['2023-01-01', '2023-01-01', '2023-01-02', '2023-01-02'],
    'Location': ['A', 'B', 'A', 'B'],
    'Value': [10, 20, 15, 25]
}
df = pd.DataFrame(data)

# Pivot the DataFrame
pivoted_df = df.pivot(index='Date', columns='Location', values='Value')

The resulting pivoted_df will look like this:

Date A B
2023-01-01 10 20
2023-01-02 15 25

In this example:

  • The Date column becomes the index.
  • The unique values in the Location column become the new columns.
  • The Value column fills the cells of the new DataFrame.

This transformation is useful for analyzing and visualizing data in a more structured format.

0 Comments

no data
Be the first to share your comment!