Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Pandas DataFrame Reindexing a certain data from 0

My code is given below: I extracted a part of data from original dataframe. I wanted the newdata frame to have index starting from 0. Strangely, it carries the old index with it. I tried the reset_index(), but it didn't work. Any inputs?

a = [10,20,30,40,50,60]
a = pd.DataFrame(a,columns=['Data'])
print(a)
b = pd.DataFrame(a['Data'][3:5])
print(b)
b.reset_index()
print(b)

The output is:

      Data
0    10
1    20
2    30
3    40
4    50
5    60
   Data
3    40
4    50
   Data
3    40
4    50

I was expecting the index of b dataframe to be as:

Data
0    40
1    50

I tried the following code as suggested by jezrael which is my accepted answer and it perfectly worked:

b.reset_index(inplace=True,drop=True)
print (b)

The new output is:

    Data
0    40
1    50

But, I don't want index column.

like image 423
Msquare Avatar asked Oct 22 '25 16:10

Msquare


1 Answers

You forget assign back and add drop=True parameter for remove original index:

b = b.reset_index(drop=True)
print(b)
   Data
0    40
1    50

Or use:

b.reset_index(inplace=True, drop=True)
print(b)
   Data
0    40
1    50

If not use drop=True is created new column with original index values:

b = b.reset_index()
print(b)
   index  Data
0      3    40
1      4    50
like image 166
jezrael Avatar answered Oct 25 '25 06:10

jezrael