使用Pandas写入Excel时移除Location列方括号的问题
解决Pandas写入Excel时Location列带方括号的问题
你的Location数据是字符串列表,但写入Excel后该列始终带着[],核心问题是你当前代码是先把原始数据写入Excel,再修改DataFrame,这时候的修改不会同步到已经写入的文件里。
修正方案
把Location列的处理逻辑移到创建DataFrame之后、写入Excel之前,直接将列表转成换行分隔的字符串,自然去掉方括号:
def create_excel_with_format(headers, values, full_file_name_with_path): # 创建DataFrame df = pd.DataFrame(data=values, columns=headers) # 先处理Location列:把列表转成换行分隔的字符串,同时去掉方括号 if 'Location' in df.columns: # 将每个列表元素用换行符连接,直接消除[] df["Location"] = df["Location"].apply(lambda x: "\n".join(x)) with pd.ExcelWriter(full_file_name_with_path) as writer: df.to_excel(writer, index=False) workbook = writer.book worksheet = writer.sheets['Sheet1'] # 设置Location列的格式(换行、宽度) if 'Location' in df.columns: twrap = workbook.add_format({"text_wrap": True}) idx_location = df.columns.get_loc("Location") worksheet.set_column(idx_location, idx_location, 60, twrap) header_format = workbook.add_format({ 'bold': True, 'border': False, 'text_wrap': False, 'font_size':13}) for col_num, value in enumerate(df.columns.values): worksheet.write(0, col_num, value, header_format)
关键改动说明
- 提前处理Location列:用
apply(lambda x: "\n".join(x))直接将列表类型的字段转为换行分隔的字符串,完全避免了列表转字符串时自动添加的[]。 - 移除原代码中在
ExcelWriter上下文里修改df的逻辑,因为此时df已经写入文件,修改不会生效。
处理后Excel中的Location列会显示为:
Pico\Medman\FluidTransferTests\packages.config EchoNET\ExternalData\PadsServiceConsole\PadsServiceConsole.csproj EchoNET\ExternalData\SerialNumberDataBase\SerialNumberDataBase.csproj EchoNET\UI\E2C\E2CApp\E2CApp.csproj Fixtures\PADS\PADSClient\PADSClient.csproj
内容的提问来源于stack exchange,提问作者nikhil
相关产品推荐
相关产品推荐

