Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extraneous empty row after header

Tags:

python

pandas

This is my code:

import pandas as pd

data = [('index', 'name', 'age'), ('idx01', 'John', 23), ('idx02', 'Marc', 32), ('idx03', 'Helena', 12)]

columns = data.pop(0)
df = pd.DataFrame(data, columns=columns).set_index(columns[0])
print(df)

Which produces:

         name  age
index               <----- Where is this row coming from?
idx01    John   23
idx02    Marc   32
idx03  Helena   12

I do not understand where is the empty index row coming from. Is this a header, or a data row? Why is it being generated? It is just an empty row, but other dataframes (generated with other methods) in my code do not have that empty row. I would like to make sure my data is not corrupted somehow.

like image 751
blueFast Avatar asked Sep 12 '25 09:09

blueFast


1 Answers

It is no empty row. Try remove index.name by df.index.name=None and no empty row. If you set_index from column with name, index.name is column name like index in this sample.

import pandas as pd

data = [('index', 'name', 'age'), 
        ('idx01', 'John', 23), 
        ('idx02', 'Marc', 32), 
        ('idx03', 'Helena', 12)]

columns = data.pop(0)
df = pd.DataFrame(data, columns=columns).set_index(columns[0])
print(df)
         name  age
index             
idx01    John   23
idx02    Marc   32
idx03  Helena   12

df.index.name=None
print(df)
         name  age
idx01    John   23
idx02    Marc   32
idx03  Helena   12
like image 164
jezrael Avatar answered Sep 13 '25 23:09

jezrael