我有一个标准的 Excel 模板,我从不同的实体收集有关按站点和产品划分的销售数据的信息,如第一个表所示。我想编写一个 python 代码将第一个表转换为第二个表,以便它只收集估计数据。我还想将这个表从今年起延长 5 年。 (即对于 2024 年,应延长至 2029 年)。如果没有可用数据,请输入0。有人可以帮忙编写代码吗?
表1
实体:苹果
年月实际/估计现场产品 2024 年 1 月 A 100 87 2024 年 2 月 A 90 31 2024 年 3 月 34 45 2024 年 4 月 25 日 31 日 2024 年 5 月 E 46 49 2024 年 6 月 E 68 54 2024 年 7 月 E 42 21 2024 年 8 月 东 133 135 2024 年 9 月 东 43 24 2024 年 10 月 E 52 14 2024 年 11 月 E 187 56 2024 年 12 月 东 38 37
表2
网站 EEEEEEEEE 2024 2024 2024 2024 2024 2024 2024 2024 实体 5 月 6 月 7 月 8 月 9 月 10 月 11 月 12 月 苹果 46 68 42 133 43 52 187 38
import pandas as pd
import datetime
df = pd.read_excel('APPLE.xlsx')
df = df[df['Actual/Estimate'] == 'E']
df = df[['Site', 'Year', 'Month', 'Product', 'Total']]
current_year = datetime.datetime.now().year
years = list(range(current_year, current_year + 6))
pivot_df = df.pivot(index='Entity', columns=['Month', 'Year'], values=['Product', 'Total'])
pivot_df.columns = pivot_df.columns.map(lambda x: f"{x[1]} {x[0]}")
pivot_df.index.name = ''
for year in years:
if year not in pivot_df.columns:
pivot_df[year] = 0
pivot_df = pivot_df.sort_index(axis=1)
output_df = pivot_df.T
print(output_df)
import pandas as pd
# Load the data from an Excel file
df = pd.read_excel('APPLE.xlsx')
# Filter rows where 'Actual/Estimate' is 'E' for estimates
df = df[df['Actual/Estimate'] == 'E']
# We focus only on the relevant columns, which seem to be 'Site', 'Year', 'Month', 'Product'
df = df[['Site', 'Year', 'Month', 'Product']]
# Ensure 'Year' is an integer, if it's read as string or float
df['Year'] = df['Year'].astype(int)
# Set up the range of years we want in our data
current_year = 2024 # Given in the question
extend_years = 5 # Extend by 5 years
years = list(range(current_year, current_year + extend_years + 1))
# Create a pivot table with 'Entity' as index, 'Year' and 'Month' as columns, and 'Product' as values
pivot_df = df.pivot_table(index='Site', columns=['Year', 'Month'], values='Product', fill_value=0)
# Reindex the DataFrame to ensure all required years and months are present
# This step ensures that if some (Year, Month) combination is missing, it's filled with zeros.
new_columns = pd.MultiIndex.from_product([years, ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']], names=['Year', 'Month'])
pivot_df = pivot_df.reindex(new_columns, fill_value=0, axis=1)
# Simplify column headers by joining year and month
pivot_df.columns = [f"{year} {month}" for year, month in pivot_df.columns]
# Transpose the DataFrame for the desired output format
output_df = pivot_df.transpose()
# Save the transformed data to a new Excel file
output_df.to_excel('transformed_data.xlsx')
# Optionally, display the DataFrame to verify
print(output_df)