Reputation: 21971
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?
Upvotes: 51
Views: 304161
Reputation: 1
Removing header column from pandas DataFrame. It can be done without writing out to csv and then reading again.
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)
Upvotes: 0
Reputation: 2137
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]
Upvotes: 0
Reputation: 11
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
Upvotes: 1
Reputation: 181
I had the same problem but solved it in this way:
df = pd.read_csv('your-array.csv', skiprows=[0])
Upvotes: 14
Reputation: 19
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)
Upvotes: 1
Reputation: 1805
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)
Upvotes: 26
Reputation: 862661
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
Upvotes: 56