python读取某表格所有sheet,固定某几列数据不删,并根据合计该行数据,若合计行数值低于90则删除这列数据
时间: 2024-04-29 15:21:17 浏览: 127
以下是可以实现该功能的Python代码:
```python
import pandas as pd
# 读取Excel文件,返回所有sheet的DataFrame列表
def read_excel(file):
xl = pd.ExcelFile(file)
dfs = []
for sheet in xl.sheet_names:
df = xl.parse(sheet)
dfs.append(df)
return dfs
# 固定不删的列
fixed_cols = ['名称', '数量']
# 检查合计行数值是否低于90
def check_total(row):
total = row.sum()
return total >= 90
# 处理每个DataFrame
def process_df(df):
# 根据合计行筛选出需要删除的列
to_drop = []
for col in df.columns:
if col not in fixed_cols:
if not check_total(df[col]):
to_drop.append(col)
# 删除需要删除的列
df.drop(to_drop, axis=1, inplace=True)
# 主函数
def main():
file = 'example.xlsx'
dfs = read_excel(file)
for df in dfs:
process_df(df)
# 将处理后的DataFrame写回Excel文件
with pd.ExcelWriter(file) as writer:
for i, df in enumerate(dfs):
df.to_excel(writer, sheet_name=f'Sheet{i+1}', index=False)
if __name__ == '__main__':
main()
```
说明:
- `read_excel` 函数使用 Pandas 库的 `ExcelFile` 和 `parse` 函数读取 Excel 文件,返回所有 sheet 的 DataFrame 列表。
- `fixed_cols` 列表存储需要固定不删的列的列名。
- `check_total` 函数用于检查合计行数值是否低于 90,返回布尔值。
- `process_df` 函数用于处理每个 DataFrame,首先根据合计行筛选出需要删除的列,然后使用 DataFrame 的 `drop` 方法删除这些列。
- `main` 函数是程序的主入口,读取 Excel 文件,处理每个 DataFrame,最后将处理后的 DataFrame 写回 Excel 文件。
- 程序使用了 Pandas 库的 `ExcelWriter` 和 `to_excel` 函数将 DataFrame 写回 Excel 文件。
注意:
- 本程序假设每个 sheet 的合计行都在最后一行,且合计行的起始单元格是 A1。
- 本程序仅处理数值类型的列,不处理其他类型的列。如果需要处理其他类型的列,可以根据实际情况修改代码。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)