<生信交流与合作请关注公众~号@生信探索>
实际数据分析中遇到需求,把某个Excel表格按照某一列分为多个sheet,并且要求如果某个key对应的行数较少应该合并到一个sheet中。
import pandas as pd
import bioquest as bq # https://jihulab.com/BioQuest/bioquest
从网上找随便了个数据做演示用
input_file=r"https://gitee.com/zhjx19/chaoyanghospital/raw/master/%E6%9C%9D%E9%98%B3%E5%8C%BB%E9%99%A22018%E5%B9%B4%E9%94%80%E5%94%AE%E6%95%B0%E6%8D%AE.xlsx"
output_file=r"朝阳医院.xlsx"
key='商品名称'
读如数据,删除商品名称为na的行
data = pd.read_excel(input_file)
data.dropna(subset=key,inplace=True)
替换/
为每
,删除特殊字符(因为不能作为sheetname)
data.loc[:,key] = bq.st.replaces(string=data.loc[:,key],pattern=r"/",repl="每")
data.loc[:,key] = bq.st.replaces(string=data.loc[:,key],pattern=r"[\\*?:/\[\]]",repl="")
如果某个key对应的行数少于50则合并在合并的药物
这个sheet中,其他的key单独存在对应的sheet中
keys=data.loc[:,key].unique().tolist()
few_dict = {}
single_dict = {}
for i in keys:
data_sub = data.groupby(key).get_group(i)
if data_sub.shape[0]<50:
few_dict[i] = data_sub
else:
single_dict[i] = data_sub
第一次写出合并的药物sheet
few = pd.concat(few_dict,ignore_index=True)
few.to_excel(output_file, sheet_name="合并的药物", index=False)
循环append sheet,最后close
writer = pd.ExcelWriter(output_file, engine='openpyxl',mode="a")
for k,v in single_dict.items():
v.to_excel(writer, sheet_name=f"{k}", index=False)
writer. Close()
标签:loc,file,sheet,某列,Python,Excel,dict,key,data
From: https://www.cnblogs.com/BioQuest/p/17436266.html