Sure, here is the pivot table using pandas library:
import pandas as pd
import numpy as np
# Create a sample dataset
data = {
'Date': pd.date_range(start='2023-01-01', end='2023-12-31', freq='D'),
'Product': np.random.choice(['A', 'B', 'C'], size=365),
'Region': np.random.choice(['North', 'South', 'East', 'West'], size=365),
'Sales': np.random.randint(100, 1000, size=365)
}
df = pd.DataFrame(data)
# Create a pivot table
pivot = pd.pivot_table(df, values='Sales', index=['Region'], columns=['Product'], aggfunc='sum')
print("Pivot Table:")
print(pivot)
# Accessing rows
print("\nAccessing rows:")
print("First row:")
print(pivot.iloc[0])
print("\nRow for 'North' region:")
print(pivot.loc['North'])
# Accessing columns
print("\nAccessing columns:")
print("First column:")
print(pivot.iloc[:, 0])
print("\nColumn for Product 'A':")
print(pivot['A'])
# Accessing specific cells
print("\nAccessing specific cells:")
print("Sales for Product 'A' in 'North' region:")
print(pivot.at['North', 'A'])
# Iterating through rows
print("\nIterating through rows:")
for index, row in pivot.iterrows():
print(f"Region: {index}, Sales: {row.to_dict()}")
# Iterating through columns
print("\nIterating through columns:")
for column in pivot.columns:
print(f"Product: {column}, Sales: {pivot[column].to_dict()}")