Home > Back-end >  How to replace pandas dataframe index values without using inplace and without canceling the index n
How to replace pandas dataframe index values without using inplace and without canceling the index n

Time:09-29

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].

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.

CodePudding user response:

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

CodePudding user response:

Do you want something like this?

import pandas as pd

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

df = pd.DataFrame(data)
df.index.name = "foo"
df.index=df.index /10
  • Related