xxxxxxxxxx
How to convert index of a pandas dataframe into a column
df = df.reset_index(level=0)
df['index1'] = df.index
xxxxxxxxxx
import pandas as pd
# Reset index
df = df.reset_index()
# Display DataFrame
print(df)
xxxxxxxxxx
df.reset_index(drop=True) # Totally Discard the index information
df.reset_index() # Replace index in a new column
xxxxxxxxxx
import pandas as pd
data = {'Name': ['Bob', 'Dilan', 'is ', 'alive', '!']}
index = {'a', 'b', 'c', 'd', 'e'}
df = pd.DataFrame(data, index)
df
Name
b Bob
a Dilan
d is
c alive
e !
df.reset_index(inplace = True)
df
index Name
0 b Bob
1 a Dilan
2 d is
3 c alive
4 e !
xxxxxxxxxx
df.reset_index(
drop=True, # to avoid the old index being added as a column
inplace=False) # (default) return df with the new index, i.e. do not create a new object