Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing header column from pandas dataframe

Tags:

python

pandas

I have the foll. dataframe:

df

   A   B 0  23  12 1  21  44 2  98  21 

How do I remove the column names A and B from this dataframe? One way might be to write it into a csv file and then read it in specifying header=None. is there a way to do that without writing out to csv and re-reading?

like image 684
user308827 Avatar asked Apr 18 '16 07:04

user308827


People also ask

How do I skip the header in pandas?

You can set the header option to None to ignore header.


2 Answers

I think you cant remove column names, only reset them by range with shape:

print df.shape[1] 2  print range(df.shape[1]) [0, 1]  df.columns = range(df.shape[1]) print df     0   1 0  23  12 1  21  44 2  98  21 

This is same as using to_csv and read_csv:

print df.to_csv(header=None,index=False) 23,12 21,44 98,21  print pd.read_csv(io.StringIO(u""+df.to_csv(header=None,index=False)), header=None)     0   1 0  23  12 1  21  44 2  98  21 

Next solution with skiprows:

print df.to_csv(index=False) A,B 23,12 21,44 98,21  print pd.read_csv(io.StringIO(u""+df.to_csv(index=False)), header=None, skiprows=1)     0   1 0  23  12 1  21  44 2  98  21 
like image 72
jezrael Avatar answered Oct 14 '22 17:10

jezrael


How to get rid of a header(first row) and an index(first column).

To write to CSV file:

df = pandas.DataFrame(your_array) df.to_csv('your_array.csv', header=False, index=False) 

To read from CSV file:

df = pandas.read_csv('your_array.csv') a = df.values 

If you want to read a CSV file that doesn't contain a header, pass additional parameter header:

df = pandas.read_csv('your_array.csv', header=None) 
like image 24
Max Avatar answered Oct 14 '22 16:10

Max