Pandas 数据框在写入 xlsx 时从列表字符串中删除方括号

问题描述 投票:0回答:1

位置数据是我得到的字符串列表。当我使用 Pandas 写入 xlsx 时,它总是在这 1 列两边加上方括号。

这就是我一直在尝试的:

def create_excel_with_format(headers,values,full_file_name_with_path):
   
   #Write to CSV in xlsx format with indentation.
   df = pd.DataFrame(data=values,columns=headers)
   #df = df.set_axis(df.index*2 + 1).reindex(range(len(df)*2)) #Create a blank row after every row.

   with pd.ExcelWriter(full_file_name_with_path) as writer:
        df.to_excel(writer, index=False)

        workbook  = writer.book
        worksheet = writer.sheets['Sheet1']      
        #Write the location each comma separated in new line if exists (For Nuget exists and thirdparty no).
        if 'Location' in df:
            location = df["Location"].str.join("\n")
            df["Location"] = location.str.replace('[', repl = '', regex = False).str.replace(']', repl  = '', regex = False)
            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)

   #pd.read_csv(full_file_name_with_path).iloc[:, 1:].apply(lambda x: x.replace(r"[\[\]]","",regex=True)).to_csv(full_file_name_with_path)

当我看到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']

如何去掉方括号?

python pandas dataframe xlsx
1个回答
1
投票

在写入 Excel 之前将列表转换为字符串。下面的块会将 df 中的任何列表转换为逗号分隔的字符串,您可以将分隔符更改为您在连接命令中喜欢的任何内容。

for index,row in df.iterrows():
    for col in list(df.columns):
            if isinstance(row[col], list):
                    row[col] = ", ".join(row[col])
© www.soinside.com 2019 - 2024. All rights reserved.