pandas to_csv comma were replace with a

时间:2015-11-12 11:55:12

标签: python csv pandas

I want to write my data into csv file using Pandas DataFrame and my codes are:

>>> for _, dataframe in my_data.items():
        dataframe.to_csv('./my_file.csv', 'a')

But, problems are:

  • when I open the my_file.csv, the comma "," were replaced with 'a' like this: 1,2,3 4,5,6 But it is: 1a2a3 4a5a6

  • and I am using append mode in to_csv function, but the previous data were cleared, I am confused!

2 个答案:

答案 0 :(得分:3)

请参阅API

您的代码等于

dataframe.to_csv('./my_file.csv', sep = 'a')

但你想要

dataframe.to_csv('./my_file.csv', mode = 'a')

供参考:http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html

答案 1 :(得分:1)

The reason you're seeing an 'a' is because the second argument for to_csv() is the seperater. Change it to dataframe.to_csv('./my_file.csv', ','), or omit the last part altogether dataframe.to_csv('./my_file.csv')

The a does not refer to append mode (I assume thats what you're talking about when you say append mode). Which means every time your loop runs, my_file.csv is being overwritten by the latest dataframe going through the loop.

I'm not sure what you want your resulting file(s) to look like, but you'll want to make sure you either use a different filename for each dataframe, or join all your dataframes together first and then write the new larger dataframe to a single csv file.