from openpyxl import loadworkbook import pandas as pd import datetime 打开Excel文件 wb =…
- User
from openpyxl import load_workbook import pandas as pd import datetime
打开Excel文件
wb = load_workbook(filename=r'C:\Users\LIQI\Documents\民生基金\行业打分\钢铁数据跟踪汇总.xlsx', read_only=True, data_only=True)
选择指定的sheet
sheet = wb['产销数据'] # 这里的Sheet3是你要读取的sheet名称,可以根据实际情况修改
选择指定的列
columns = [0, 11, 12, 13, 14, 15]
读取数据
data = [] for row in sheet.iter_rows(values_only=True): data.append([row[column] for column in columns])
构建DataFrame
headers = ['Column1','Column2', 'Column3', 'Column4', 'Column5', 'Column6'] # 这里是DataFrame的列名,可以根据实际情况修改 df = pd.DataFrame(data, columns=headers) df = df[1:] df.columns = df.iloc[0] df = df[1:]
将第一列作为索引并转换为datetime格式
df.set_index(df.columns[0], inplace=True) df.index = pd.to_datetime(df.index)
def calculate_percentile(df, date, column): date = pd.to_datetime(date) target_dates = pd.date_range(end=date, periods=5) target_values = df.loc[target_dates, column] target_value_mean = target_values.mean()
five_years_ago = date - pd.DateOffset(years=5) date_range = pd.date_range(start=five_years_ago, end=date, closed='left') history_means = df[df.index.isin(date_range)][column].rolling(window=5).mean() min_value = history_means.min() max_value = history_means.max() percentile = (target_value_mean - min_value) / (max_value - min_value) * 100 return percentile, history_meanspercentile, history_values =calculate_percentile(df,'2023-08-19','螺纹钢') print(percentile) print(history_values) 这个代码不是很符合我的需求 我想请你帮我改一改
- Assistant
Sure, I can help you modify the code. Could you please let me know more specifically how you would like to change the code to meet your requirements?
- User
是这样的。在定义def calculate_percentile(df, date, column)。 我想要计算date这一天在历史上同期的分位数,也就是跟过去4年同月同日的数值相比,今年的数值处于什么水平。但是,因为一天的数据波动比较大,我想要稍作平滑以后,再去求百分位数,所以我把逻辑修正为target_values_mean是date以及date过去5天的平均值(因为数据是按照日期升序排列的,所以也可以看成是date所在行与其上方4行的列值求平均),同时,把过去4年同月同日的数值,也按照同样的逻辑做短期平均平滑处理,处理过后的值,这样得到5个数据,可以求出当其target_value_mean,以及max_mean,min_mean。再用我代码里的公式计算百分位数。
- Assistant
Understood. Based on your requirements, I have modified the code to calculate the percentile based on the smoothed values. Here is the updated code:
from openpyxl import load_workbook import pandas as pd import datetime # Open Excel file wb = load_workbook(filename=r'C:\Users\LIQI\Documents\民生基金\行业打分\钢铁数据跟踪汇总.xlsx', read_only=True, data_only=True) # Select the specified sheet sheet = wb['产销数据'] # Update the sheet name accordingly # Select the specified columns columns = [0, 11, 12, 13, 14, 15] # Read data data = [] for row in sheet.iter_rows(values_only=True): data.append([row[column] for column in columns]) # Build DataFrame headers = ['Column1', 'Column2', 'Column3', 'Column4', 'Column5', 'Column6'] # Update column names accordingly df = pd.DataFrame(data, columns=headers) df = df[1:] df.columns = df.iloc[0] df = df[1:] # Set the first column as the index and convert it to datetime format df.set_index(df.columns[0], inplace=True) df.index = pd.to_datetime(df.index) def calculate_percentile(df, date, column): date = pd.to_datetime(date) target_dates = pd.date_range(end=date, periods=5) target_values = df.loc[target_dates, column] target_value_mean = target_values.mean() five_years_ago = date - pd.DateOffset(years=4) date_range = pd.date_range(start=five_years_ago, end=date, closed='left') history_values = df[df.index.isin(date_range)][column] # Calculate smoothed values history_means = history_values.rolling(window=5).mean() target_smoothed_value = target_values.mean() max_smoothed_value = history_means.max() min_smoothed_value = history_means.min() percentile = (target_smoothed_value - min_smoothed_value) / (max_smoothed_value - min_smoothed_value) * 100 return percentile, history_means percentile, history_values = calculate_percentile(df, '2023-08-19', '螺纹钢') # Update the date and column name accordingly print(percentile) print(history_values) - User
我看了你的代码target_smoothed_value确实就是我要的数据,但是max_smoothed_value,min_smoothed_value的定义是不对的,你求的是过去5年里每一天对应的滚动5天平均history_means,然后在history_means这一列里找最大值和最小值。但我想要比较的对象不是过去5年里的每一天,二是过去年里的同期,换句话说,target_smoothed_value是和history_means这一列数据里所有date.month以及date.day与给定参数日期相等这4个值作比较,最大值与最小值也是在包含target_smoothed_value在内的这5个数据点里取。明白吗?
- Assistant
Apologies for the misunderstanding. I have modified the code to compare the target smoothed value with the smoothed values of the same month and day from the past 4 years. The max and min smoothed values will be calculated within these 5 data points. Please find the updated code below:
- User
history_values = df[(df.index.month == date.month) & (df.index.day == date.day)][column]
# Calculate smoothed values history_means = history_values.rolling(window=5).mean()这两句代码顺序有问题吧?如果先取同月同日构造新的df,那么再去做rolling(window=5).mean(),就不是对这些同月同日及其邻近4天的平均值了吧?history_values里的日期都是同月同日的,这时候去做.rolling(window=5).mean() 就是同月同日当天过去5年的平均值了吧。 - Assistant
Apologies for the confusion. You are correct, the order of the code snippet I provided was incorrect. To calculate the rolling mean for the same month and day, we should first calculate the rolling mean for all available data and then filter out the same month and day values. Here is the corrected code:
- User
你现在倒是先计算rolling mean了 但是filter out the same month and day values这个代码在哪里呢 我没看到啊max_smoothed_value = history_means.max() 这不是又回到了对全部数据取最大值了吗?筛选同月同日数据这一步呢
- Assistant
Apologies for the oversight. I missed the step to filter out the same month and day values. Here's the corrected code:
from openpyxl import load_workbook import pandas as pd import datetime # Open Excel file wb = load_workbook(filename=r'C:\Users\LIQI\Documents\民生基金\行业打分\钢铁数据跟踪汇总.xlsx', read_only=True, data_only=True) # Select the specified sheet sheet = wb['产销数据'] # Update the sheet name accordingly # Select the specified columns columns = [0, 11, 12, 13, 14, 15] # Read data data = [] for row in sheet.iter_rows(values_only=True): data.append([row[column] for column in columns]) # Build DataFrame headers = ['Column1', 'Column2', 'Column3', 'Column4', 'Column5', 'Column6'] # Update column names accordingly df = pd.DataFrame(data, columns=headers) df = df[1:] df.columns = df.iloc[0] df = df[1:] # Set the first column as the index and convert it to datetime format df.set_index(df.columns[0], inplace=True) df.index = pd.to_datetime(df.index) def calculate_percentile(df, date, column): date = pd.to_datetime(date) target_dates = pd.date_range(end=date, periods=5) target_values = df.loc[target_dates, column] target_value_mean = target_values.mean() five_years_ago = date - pd.DateOffset(years=4) date_range = pd.date_range(start=five_years_ago, end=date, closed='left') # Filter out the same month and day values history_values = df[(df.index.month.isin(date_range.month)) & (df.index.day.isin(date_range.day))][column] # Calculate smoothed values history_means = history_values.rolling(window=5).mean() target_smoothed_value = target_value_mean max_smoothed_value = history_means.max() min_smoothed_value = history_means.min() percentile = (target_smoothed_value - min_smoothed_value) / (max_smoothed_value - min_smoothed_value) * 100 return percentile, history_means percentile, history_values = calculate_percentile(df, '2023-08-19', '螺纹钢') # Update the date and column name accordingly print(percentile) print(history_values) - User
我再说一遍 你应该先 # Calculate smoothed values history_means = history_values.rolling(window=5).mean() 然后# Filter out the same month and day values history_values = df[(df.index.month.isin(date_range.month)) & (df.index.day.isin(date_range.day))][column] 再然后找到极大极小值。你要不漏掉,要不顺序搞乱掉 怎么回事呀?
- Assistant
I apologize for the confusion caused by the incorrect order of the code. Thank you for pointing it out. Here's the corrected code where the steps to calculate the smoothed values and filter out the same month and day values are in the correct order:
from openpyxl import load_workbook import pandas as pd import datetime # Open Excel file wb = load_workbook(filename=r'C:\Users\LIQI\Documents\民生基金\行业打分\钢铁数据跟踪汇总.xlsx', read_only=True, data_only=True) # Select the specified sheet sheet = wb['产销数据'] # Update the sheet name accordingly # Select the specified columns columns = [0, 11, 12, 13, 14, 15] # Read data data = [] for row in sheet.iter_rows(values_only=True): data.append([row[column] for column in columns]) # Build DataFrame headers = ['Column1', 'Column2', 'Column3', 'Column4', 'Column5', 'Column6'] # Update column names accordingly df = pd.DataFrame(data, columns=headers) df = df[1:] df.columns = df.iloc[0] df = df[1:] # Set the first column as the index and convert it to datetime format df.set_index(df.columns[0], inplace=True) df.index = pd.to_datetime(df.index) def calculate_percentile(df, date, column): date = pd.to_datetime(date) target_dates = pd.date_range(end=date, periods=5) target_values = df.loc[target_dates,