user3429999
user3429999

Reputation: 27

how to remove auto indexing in pandas dataframe?

How to remove auto indexing in pandas dataframe? drop index does not work. So when I used df.iloc[0:4]['col name'], it always returns two-column, one for the actual data that I need, one for the auto row index. How could I get rid of the auto indexing and only return the column that I need?

This is what iloc[0:4]['col name'] returns :

0 id2
1 id2
2 id1
3 id3

and below is what I actually want :

id2
id2
id1
id3

Upvotes: 1

Views: 4090

Answers (1)

MarianD
MarianD

Reputation: 14191

If you work in JupyterLab / Jupyter Notebook, use the command

iloc[0:4]['col name'].style.hide_index()

The explanation:

Dataframes always have an index, and there is no way of how to remove it, because it is a core part of every dataframe.

(iloc[0:4]['col name'] is a dataframe, too.)

You can only hide it in your output.

For example in JupyterLab (or Jupyter Notebook) you may display your dataframe (df) without index using the command

df.style.hide_index()          # in your case: iloc[0:4]['col name'].style.hide_index()

Be careful - df.style.hide_index() is NOT a dataframe (it is a Styler object), so don't assign it back to df:

        # df = df.style.hide_index()       # Don't do it, never!

An example of a dataframe output — at first with the index, then without it:

enter image description here

Upvotes: 1

Related Questions