It seems strange to me that pandas.read_csv
is not a direct reciprocal function to df.to_csv
. In this illustration, notice how when using all the default settings the original and final DataFrames differ by the "Unnamed" column.
In [1]: import pandas as pd
In [2]: orig_df = pd.DataFrame({'AAA' : [4,5,6,7], 'BBB' : [10,20,30,40],'CCC' : [100,50,-30,-50]}); orig_df
Out[2]:
AAA BBB CCC
0 4 10 100
1 5 20 50
2 6 30 -30
3 7 40 -50
[4 rows x 3 columns]
In [3]: orig_df.to_csv('test.csv')
In [4]: final_df = pd.read_csv('test.csv'); final_df
Out[4]:
Unnamed: 0 AAA BBB CCC
0 0 4 10 100
1 1 5 20 50
2 2 6 30 -30
3 3 7 40 -50
[4 rows x 4 columns]
It seems the default read_csv
should instead be
In [6]: final2_df = pd.read_csv('test.csv', index_col=0); final2_df
Out[7]:
AAA BBB CCC
0 4 10 100
1 5 20 50
2 6 30 -30
3 7 40 -50
[4 rows x 3 columns]
or the default to_csv
should instead be
In [8]: df.to_csv('test2.csv', index=False)
which when read gives
In [9]: pd.read_csv('test2.csv')
Out[9]:
AAA BBB CCC
0 4 10 100
1 5 20 50
2 6 30 -30
3 7 40 -50
[4 rows x 3 columns]
(Perhaps this should instead be sent to the developer/s but I am genuinely interested why this is the default behavior. Hopefully it also can help someone else avoid the confusion I had).