[Solved] Reset Column Index Pandas?

>>> data = data.drop(data.columns[[1,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]], axis=1)
>>> data = data.drop(data.index[[0,1]],axis = 0)
>>> print(data.head())
             0         2    3    4    20
2  500292014600       .00  .00  .00  NaN
3  500292014600    100.00  .00  .00  NaN
4  500292014600  11202.00  .00  .00  NaN
>>> data = data.reset_index(drop = True)
>>> print(data.head())
              0         2    3    4    20
 0  500292014600       .00  .00  .00  NaN
 1  500292014600    100.00  .00  .00  NaN
 2  500292014600  11202.00  .00  .00  NaN

How come when i use df.reset_index the index of my columns is not reset?
How do I go about resetting this index to 0,1,2,3,4?

Enquirer: MrClean

||

Solution #1:

Try replacing the column names:

>>> import numpy as np
>>> import pandas as pd

>>> my_data = [[500292014600, .00, .00, .00, np.nan],
              [500292014600, 100.00, .00, .00, np.nan], 
              [500292014600, 11202.00, .00, .00, np.nan]]
>>> df = pd.DataFrame(my_data, columns=[0,2,3,4,20])
>>> df
              0        2    3    4  20
0  500292014600      0.0  0.0  0.0 NaN
1  500292014600    100.0  0.0  0.0 NaN
2  500292014600  11202.0  0.0  0.0 NaN

>>> df.columns = range(df.shape[1])
>>> df
              0        1    2    3   4
0  500292014600      0.0  0.0  0.0 NaN
1  500292014600    100.0  0.0  0.0 NaN
2  500292014600  11202.0  0.0  0.0 NaN
Respondent: Patrick Nieto

Solution #2:

Try the following:

df = df.T.reset_index(drop=True).T
Respondent: Pablo Fonseca

Solution #3:

In pandas, by index you essentially mean row index. As you can see in your data, the row index is reset after drop and reset_index().

For columns, you need to rename them, you can do something like

data.columns = [ 0,1,2,3,4]
Respondent: Vaishali

Solution #4:

If you have numpy imported with import numpy as np

simply set the columns to zero based indexes with data.columns = [np.arange(0,data.shape[1])]

Respondent: ashish patel

Solution #5:

Pure Python Implementation

We enumerate the columns of the dataframe to create an array of items. Then we map the function reversed to each item in the array. Lastly, we create and input the dictionary as the parameter columns in the data frame object method rename.

columns = dict(map(reversed, enumerate(df.columns)))
df = df.rename(columns=columns)
df.head()

Results:

              0        1    2    3   4
0  500292014600      0.0  0.0  0.0 NaN
1  500292014600    100.0  0.0  0.0 NaN
2  500292014600  11202.0  0.0  0.0 NaN
Respondent: Jeff Hernandez

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published. Required fields are marked *

New ride at Perth's Adventure World a ‘swing on steroids’ - Australasian Leisure Management npp pharma the truth about anabolic steroid drugs and professional sports