Reputation: 845
I have this example code
import pandas as pd
df = pd.DataFrame({'month': [1, 4, 7, 10],
'year': [2012, 2014, 2013, 2014],
'sale':[55, 40, 84, 31]})
df.set_index('month', inplace=True)
print(df[( df['sale'] > 40)])
which produces:
sale year
month
1 55 2012
7 84 2013
But I need
month sale year
0 1 55 2012
2 7 84 2013
where I reset the index to default index. Is there a way to change the print statement to accomplish this?
Thank you
Upvotes: 1
Views: 2615
Reputation: 51395
Simply take out the line df.set_index('month', inplace=True)
:
df = pd.DataFrame({'month': [1, 4, 7, 10],
'year': [2012, 2014, 2013, 2014],
'sale':[55, 40, 84, 31]})
print(df[( df['sale'] > 40)])
# month sale year
# 0 1 55 2012
# 2 7 84 2013
That line explicitly sets the index to the month
column, which you don't want. You could set it, and then unset it using df.reset_index()
as suggested by @Abdullah Ahmed Ghaznavi, but it seems like unnecessary work, unless you don't have control over the creation of the dataframe
Note: If, as suggested by your question, you only want to change the printed output (leaving the original dataframe totally untouched), you can use this print statement with your original process:
print(df[( df['sale'] > 40)].reset_index())
Upvotes: 3
Reputation: 2099
Use df.reset_index()
for info read docs
Check this:
import pandas as pd
df = pd.DataFrame({'month': [1, 4, 7, 10],
'year': [2012, 2014, 2013, 2014],
'sale':[55, 40, 84, 31]})
df.set_index('month', inplace=True) # here you are setting index inplace
print(df[( df['sale'] > 40)])
df.reset_index(inplace=True) # here i reset it inplace
print(df[( df['sale'] > 40)]) #updated df
It will give you output like this:
month sale year
0 1 55 2012
2 7 84 2013
As your desired output!
Hope this will help you! :)
Upvotes: 3