问题一
读取Data1中成对的ha和ac表格数据,组合成下表形式columns=['Year', 'Crop Type', 'Crop', 'Fungicide', 'Hectares', 'Active Substance'] 其中,Year和Crop Type取自表格名(e.g. 1987_Orchards_fruit_ha.xlsx) Crop列对应ha或ac表格中的行名;Fungicide列对应ha或ac表格中的列名 Hectares对应ha表格中的值;Active Substance对应ac表格中的值
开始分析前,首先对数据进行清洗与预处理,清洗后的的数据会让后续操作更加方便和准确
首先,要将异常值,缺失值,空值,都替换成0.0,其次将原始数据中“<1”的元素都替换成0.1,确保所有的数据都是数字类型
下面是代码模块
import os
import pandas as pd
# 定义清理函数,用于清理 Excel 文件中的空格和无用列
def clear():
# 遍历指定文件夹下的所有xlsx文件
folder_path = 'D:/vs/mobilenet/数据分析/爱尔兰杀菌剂数据分析/data_IR' # 请替换为你的文件夹路径
for filename in os.listdir(folder_path):
if filename.endswith(".xlsx"):
file_path = os.path.join(folder_path, filename)
# 使用pandas读取xlsx文件
df = pd.read_excel(file_path)
# 删除第一列字符串中的空格
df[df.columns[0]] = df[df.columns[0]].apply(lambda x: x.replace(' ', '') if isinstance(x, str) else x)
# 删除第一行字符串中的空格
df.columns = df.columns.to_series().apply(lambda x: x.replace(' ', '') if isinstance(x, str) else x)
# 创建一个新的DataFrame,它只包括第一列和那些不以 "Unnamed" 开头的列
df = df[df.columns[0]].to_frame().join(df.loc[:, ~df.columns.str.startswith('Unnamed')])
df.rename(columns={df.columns[0]: ''}, inplace=True)
# 重新保存xlsx文件,这将自动将所有列的宽度设为单列
df.to_excel(file_path, index=False)
# 定义