简体   繁体   English

Python Pandas.to_csv 无法将分号(;)的列导出为一列

[英]Python Pandas.to_csv unable to export columns with semicolon(;) as one column

I have a dataframe with 3 columns, but 1 of the columns contain data that is separated by a semicolon(;) during export.我有一个包含 3 列的数据框,但其中 1 列包含在导出期间由分号 (;) 分隔的数据。 I am trying to export a dataframe into a csv but my csv output data keeps getting separated into the following format when opening in excel:我正在尝试将数据框导出到 csv 中,但在 excel 中打开时,我的 csv 输出数据不断分成以下格式:

在此处输入图片说明

import pandas as pd

my_dict = { 'name' : ["a", "b"],
            'age' : [20,27],
            'tag': ["Login Location;Visit Location;Appointment Location", "Login Location;Visit Location;Appointment Location"]}

df=pd.DataFrame(my_dict)

df.to_csv('output.csv',index=False)
print('done')

I would like to have the output in excel to be:我希望excel中的输出为:

在此处输入图片说明

where the data in the tag column is intact.标签列中的数据完好无损。 I've tried adding sep=',' or delimiter=',' but it still gives me the same output.我试过添加 sep=',' 或 delimiter=',' 但它仍然给我相同的输出。

Thank you in advance,先感谢您,

John约翰

Excel does some stuff based on the fact that your file has a .csv suffix, probably using ; Excel 会根据您的文件具有.csv后缀这一事实执行一些操作,可能使用; as a default delimiter, as suggested in the comments.作为默认分隔符,如评论中所建议。

One workaround is to use the .txt suffix instead:一种解决方法是使用.txt后缀:

df.to_csv('output.txt',index=False)

then open the file in Excel, and in the Text Import Wizard specify "Delimited" and comma as separator.然后在 Excel 中打开文件,并在文本导入向导中指定“分隔”和逗号作为分隔符。

Do not pick the file in the list of previously opened files, if it's there, that won't work, you really need to do File/Open then browse the directory to find your .txt file.不要挑在先前打开的文件列表中的文件,如果它的存在,这是行不通的,你真正需要做的文件/打开然后浏览目录中找到您的.txt文件。

Thank you @Alex and @joao for your inputs, this guided me to the right direction.感谢@Alex 和@joao 的投入,这引导我走向正确的方向。 I was able to get the output I needed by forcing excel to use , as the separator.通过强制 excel 使用,作为分隔符,我能够获得我需要的输出。 By default, Excel was using tab as the delimiter, that's why it was showing me an incorrect format.默认情况下,Excel 使用制表符作为分隔符,这就是为什么它向我显示不正确的格式。 Here's the link to forcing excel to use comma as a list separator: https://superuser.com/questions/606272/how-to-get-excel-to-interpret-the-comma-as-a-default-delimiter-in-csv-files这是强制 excel 使用逗号作为列表分隔符的链接: https : //superuser.com/questions/606272/how-to-get-excel-to-interpret-the-comma-as-a-default-delimiter-在 csv 文件中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM