🚀 作者 :“码上有前”
🚀 文章简介 :Python
🚀 欢迎小伙伴们 点赞👍、收藏⭐、留言💬
python练习题
- 读获取目录下所有csv文件中的均值与偏态
- 按照均值和偏态最大值进行排序
- 完整代码
读获取目录下所有csv文件中的均值与偏态
import os
import csvdef brand_piantai(folder_path):# 读取文件夹下所有的CSV文件file_dict = {}file_mean_dict = {}for file_name in os.listdir(folder_path):if file_name.endswith(".csv"):file_path = os.path.join(folder_path, file_name)with open(file_path, 'r',encoding='utf-8') as file:reader = csv.DictReader(file)for row in reader:mean = round(float(row.get("均值")), 2)skewness = round(float(row.get("偏态")), 2)file_name_without_extension = os.path.splitext(file_name)[0]file_dict[skewness] = file_name_without_extensionfile_mean_dict[mean] = file_name_without_extension
按照均值和偏态最大值进行排序
# 按偏态的最大值进行排序sorted_file_dict = dict(sorted(file_dict.items(), reverse=True))sorted_piantai_dict = list(sorted_file_dict.items())[0]# 按均值的最大值进行排序sorted_file_mean_dict = dict(sorted(file_mean_dict.items(), reverse=True))sorted_mean_dict = list(sorted_file_mean_dict.items())[0]return sorted_piantai_dict,sorted_mean_dict
完整代码
import os
import csvdef brand_piantai(folder_path):# 读取文件夹下所有的CSV文件file_dict = {}file_mean_dict = {}for file_name in os.listdir(folder_path):if file_name.endswith(".csv"):file_path = os.path.join(folder_path, file_name)with open(file_path, 'r',encoding='utf-8') as file:reader = csv.DictReader(file)for row in reader:mean = round(float(row.get("均值")), 2)skewness = round(float(row.get("偏态")), 2)file_name_without_extension = os.path.splitext(file_name)[0]file_dict[skewness] = file_name_without_extensionfile_mean_dict[mean] = file_name_without_extension# 按偏态的最大值进行排序sorted_file_dict = dict(sorted(file_dict.items(), reverse=True))sorted_piantai_dict = list(sorted_file_dict.items())[0]# 按均值的最大值进行排序sorted_file_mean_dict = dict(sorted(file_mean_dict.items(), reverse=True))sorted_mean_dict = list(sorted_file_mean_dict.items())[0]return sorted_piantai_dict,sorted_mean_dict# 例子:读取当前文件夹下的所有CSV文件
piantai_folder_path = './example' # 当前文件夹路径
piantai,mean = brand_piantai(piantai_folder_path)piantai_cate_folder_path = './example' # 当前文件夹路径
cate_piantai,cate_mean = brand_piantai(piantai_cate_folder_path)print("cate_piantai==",cate_piantai)
print("cate_mean==",cate_mean)
# print("piantai==",list(piantai.items())[0])
# # 打印结果
# for skewness, file_name in piantai.items():
# print(f"偏态:{skewness},文件名:{file_name}")