from openpyxl import loadworkbook import pandas as pd import datetime from openpyxl…
- User
from openpyxl import load_workbook import pandas as pd import datetime from openpyxl import Workbook from openpyxl.utils.dataframe import dataframe_to_rows
打开Excel文件
wb = load_workbook(filename=r'C:\Users\LIQI\Documents\民生基金\行业打分\钢铁数据跟踪汇总.xlsx', read_only=True, data_only=True)
选择指定的sheet
sheet = wb['吨钢毛利'] # 这里的Sheet3是你要读取的sheet名称,可以根据实际情况修改
选择指定的列
columns = [0, 9, 10, 11, 12]
读取数据
data = [] for row in sheet.iter_rows(values_only=True): if all(value is None for value in row): break data.append([row[column] for column in columns])
构建DataFrame
df = pd.DataFrame(data) 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=6) date_range = pd.date_range(start=five_years_ago, end=date) history_values = df.loc[date_range, column] # 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] 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创建一个空的列表,用于存储每一天的percentile值
percentiles = []
设置起始日期
start_date = pd.to_datetime('2018-12-31')
循环遍历DataFrame的每一行
for index, row in df.iterrows(): # 检查是否满足起始日期的条件,如果不满足,则跳过计算 if index < start_date: percentiles.append(None) continue
# 获取当前行的日期和列名 date = index column = '螺纹钢' # 要计算percentile的列名,请根据实际情况修改 # 调用calculate_percentile函数计算percentile值 percentile = calculate_percentile(df, date, column) # 将percentile值添加到列表中 percentiles.append(percentile)df['Percentile'] = percentiles
创建一个空的列表,用于存储每一天的Percentile YOY值
percentile_yoy = []
循环遍历DataFrame的每一行
for index, row in df.iterrows(): # 检查是否满足起始日期的条件,如果不满足,则跳过计算 if index < start_date: percentile_yoy.append(None) continue
# 获取当前行的日期和列名 date = index column = '螺纹钢' # 要计算Percentile YOY的列名,请根据实际情况修改 # 获取上一年同期的日期 last_year_date = date - pd.DateOffset(years=1) # 检查上一年同期的日期是否在DataFrame中存在 if last_year_date in df.index: # 计算上一年同期的Percentile值 last_year_percentile = df.loc[last_year_date, 'Percentile'] # 计算Percentile YOY值 percentile_yoy_value = row['Percentile'] - last_year_percentile percentile_yoy.append(percentile_yoy_value) else: percentile_yoy.append(None) - Assistant
The error message indicates that the
appendmethod of thenew_sheetobject is missing a required argument.To fix this error, you need to pass the
iterableargument to theappendmethod. Since you are using thedataframe_to_rowsfunction fromopenpyxl.utils.dataframeto convert the DataFrame into rows, you can pass the result ofdataframe_to_rows(df, index=True, header=True)as the iterable argument to theappendmethod.Here's the corrected code snippet:
# 将DataFrame的数据逐行写入新sheet for r in dataframe_to_rows(df, index=True, header=True): new_sheet.append(r)This should resolve the TypeError and allow you to append the DataFrame rows to the new sheet.
- User
what does ® stand for?
- Assistant
The symbol "®" represents the registered trademark symbol. It is used to indicate that a particular word, phrase, logo, or symbol is a registered trademark or service mark with a government authority. It provides legal protection for the trademark owner and signifies that the mark is officially registered and protected under trademark laws.
- User
I mean what does ® stand for the code here "new_sheet.append®"
- Assistant
Apologies for the confusion. In the code snippet, the "®" is actually a placeholder in the error message and not part of the actual code. It was added in the error message to represent the missing argument in the
appendmethod.The correct code should be
new_sheet.append(r)as mentioned in the previous response. Theappend()method is used to add a row of data to the worksheet, andrrepresents each row of data that is obtained from thedataframe_to_rowsfunction. So, the correct syntax isnew_sheet.append(r)to append each row to the new sheet. - User
new_wb = Workbook() 当我运行这条代码的时候 我是不是应该能看到一个新的工作表被打开?还是这个打开是在后台操作的 我在桌面看不到相关信息?
- Assistant
The
Workbook()function from theopenpyxllibrary creates a new workbook object in memory. It does not automatically open a new workbook in your Excel application that would be visible on your desktop.The workbook created using
Workbook()exists in the memory of your Python program and can be modified, filled with data, and saved to a file as needed. If you want to view the workbook in your Excel application, you will need to save it to a file and then open that file manually.To save the workbook to a file, you can use the
savemethod of the workbook object. For example:new_wb.save('path/to/save/workbook.xlsx')Replace
'path/to/save/workbook.xlsx'with the desired file path where you want to save the workbook. Once the workbook is saved, you can navigate to that file location and open it using your Excel application to view the contents of the workbook.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.