Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to replace pandas dataframe index values without using inplace and without canceling the index name?

It seems that all the methods found around use inplace but I read that it is discouraged.

Consider the following code

import pandas as pd

data = {
  "col1": [420, 380, 390],
  "col2": [50, 40, 45]
}

df = pd.DataFrame(data)
df.index.name = "foo"

Next, imagine that later on I have to change the index values with these values [0.0,0.1,0.2].

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What I did is

df.index = [0.0,0.1,0.2]

but then df.index.name is empty (I expected "foo").

I kinda understand why (you completely override the attribute df.index), but then I have no idea how to change only the index values while preserving the index name.

I want to achieve this goal without using inplace.

>Solution :

Pass the index by pd.Index

df.index = pd.Index([0.0,0.1,0.2],name='foo')
df
Out[91]: 
     col1  col2
foo            
0.0   420    50
0.1   380    40
0.2   390    45
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading