Search code examples
pythonpython-3.xpandasheader

First row to header with pandas


I have the following pandas dataframe df :

import pandas as pd
from io import StringIO
s = '''\
"Unnamed: 0","Unnamed: 1"   
Objet,"Unités vendues"  
Chaise,3
Table,2
Tabouret,1
'''
df = pd.read_csv(StringIO(s))

which looks as:

  Unnamed: 0     Unnamed: 1
0      Objet  Unités vendues
1     Chaise                 3
2      Table                 2
3   Tabouret                 1

My target is to make the first row as header.

I use :

headers = df.iloc[0]
df.columns = [headers]  

However, the "0" appears in index column name (which is normal, because this 0 was in the first row).

0          Objet Unités vendues 
1         Chaise              3 
2          Table              2 

I tried to delete it in many way, but nothing work :

Neither del df.index.name from this post

Neither df.columns.name = None from this post or this one (which is the same situation)

How can I have this expected output :

           Objet Unités vendues 
1         Chaise              3 
2          Table              2 

Solution

  • what about defining that when you load your table in the first place?

    pd.read_csv('filename', header = 1)

    otherwise I guess you can just do this:

    df.drop('0', axis = 1)