Vishal Suryavanshi
Vishal Suryavanshi

Reputation: 377

how to change the index value in pandas without effecting the data

This is my data frame looks like:

day temperature windspeed event
0 1/1/2017 32 6 Rain
1 1/2/2017 35 7 Sunny
2 1/3/2017 28 2 Snow
3 1/4/2017 24 7 Snow
4 1/5/2017 32 4 Rain
5 1/6/2017 31 2 Sunny

As per my understanding i have to take the data frame and a list of index :

index = [10 ,20,30,40,50,60]
df = pd.DataFrame(df , index)
df

This code is printing some rows Nan which i dont want ..

i want my result should be ;

10 1/1/2017 32 6 Rain
20 1/2/2017 35 7 Sunny
30 1/3/2017 28 2 Snow
40 1/4/2017 24 7 Snow
50 1/5/2017 32 4 Rain
60 1/6/2017 31 2 Sunny

Upvotes: 1

Views: 60

Answers (2)

BENY
BENY

Reputation: 323276

Adding .values

index = [10 ,20,30,40,50,60]
df = pd.DataFrame(df.values , index=index,columns=df.columns)
df
Out[626]: 
         day temperature windspeed  event
10  1/1/2017          32         6   Rain
20  1/2/2017          35         7  Sunny
30  1/3/2017          28         2   Snow
40  1/4/2017          24         7   Snow
50  1/5/2017          32         4   Rain
60  1/6/2017          31         2  Sunny

Upvotes: 0

timgeb
timgeb

Reputation: 78700

You can simply issue df.index = (df.index + 1)*10.

Demo:

>>> df = pd.DataFrame([[1,2], [3,4], [5,6]])
>>> df
   0  1
0  1  2
1  3  4
2  5  6
>>> df.index = (df.index + 1)*10
>>> df
    0  1
10  1  2
20  3  4
30  5  6

Works with arbitrary columns, too:

>>> df[0] = (df[0] + 1)*10
>>> df
     0  1
10  20  2
20  40  4
30  60  6

Upvotes: 1

Related Questions