0

does anybody know how to remove the header of the index colum when applying pandas.read_csv and to_csv?

Example:

import datetime
import pandas as pd
from io import BytesIO

todays_date = datetime.datetime.now().date()
earlierDates = 2
index = pd.date_range(todays_date-datetime.timedelta(earlierDates), \
                      periods=earlierDates, freq='D')

columns = ['A', 'B']

df1 = pd.DataFrame(index=index, columns=columns)
df1.loc[index[0]] = [2, 'test1a test1b']
df1.loc[index[1]] = [1, 'test2a test2b']
df1

Out[85]: 
            A              B
2018-08-09  2  test1a test1b
2018-08-10  1  test2a test2b

df2 = pd.read_csv(BytesIO(df1.to_csv()))
df2

Out[83]: 
   Unnamed: 0  A              B
0  2018-08-09  2  test1a test1b
1  2018-08-10  1  test2a test2b

How can one remove the header "Unnamed: 0" in the above output?

Doing the following removes the header, but it also removes the date index, which is not what I want:

df3 = pd.read_csv(BytesIO(df1.to_csv(index=False)))
df3

Out[84]: 
   A              B
0  2  test1a test1b
1  1  test2a test2b

Summing up, I wonder how one removes the index column header without removing the rest of the index column when applying pd.read_csv and to_csv. I want the df that is loaded using pd.read_csv to be identical to df1 in the example above.

KJA
  • 313
  • 3
  • 14

0 Answers0