Removing header column from pandas dataframe

Question:

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?

Asked By: user308827

||

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
Answered By: 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)
Answered By: Max

I had the same problem but solved it in this way:

df = pd.read_csv('your-array.csv', skiprows=[0])
Answered By: wilma88

Haven’t seen this solution yet so here’s how I did it without using read_csv:

df.rename(columns={'A':'','B':''})

If you rename all your column names to empty strings your table will return without a header.

And if you have a lot of columns in your table you can just create a dictionary first instead of renaming manually:

df_dict = dict.fromkeys(df.columns, '')
df.rename(columns = df_dict)
Answered By: Kangand

You can first convert the DataFrame to an Numpy array, using this:

s1=df.iloc[:,0:2].values

Then, convert the numpy array back to DataFrame:

s2=pd.DataFrame(s1)

This will return a DataFrame with no Columns.
enter image description here

Answered By: lalitjoesat

This works perfectly:

To get the dataframe without the header use:

totalRow = len(df.index)
df.iloc[1: totalRow]

Or you can use the second method like this:

totalRow = df.index.stop
df.iloc[1, totalRow]
Answered By: Peter Moses

Removing header column from pandas DataFrame. It can be done without writing out to csv and re-reading.

Solution:

Replace the column names by first row of the dataframe.

df.columns = df.iloc[0,:].values

and then delete that first row of dataframe.

df = df.tail(-1)
Answered By: Anirudh Maurya
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.