Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialMark Chesney
11,747 Pointsrenaming one index in pandas DataFrame (jeffrey username)
In this Optional Challenge #2, I can't figure out how to rename an index in a pandas DataFrame row. The idea is that 'jefrey' is the proper spelling, not 'jeffrey'
users.loc['jeffrey']
jef = users.index == 'jeffrey'
# this didn't work -- attempt at creating a new row with correct name
users.loc['jefrey'] = users.loc[jef]
# this didn't work either
users[jef].index = 'jefrey'
Would I use pandas.Index.rename ? (Not sure if we learned it in this course)
2 Answers
Putra Aryotama
36,050 PointsRenaming an index is the same way as you rename a column.
Try this:
users.rename(index={'jeffrey': 'jefrey'}, inplace=True)
To check that the index name has changed:
users.loc['jefrey']
Flore W
4,744 PointsI did a workaround without using the "rename" method, but I definitely like Putra's solution better :)
# define a new dictionary with the same key and values from Jeffrey
newdict = dict(first_name='Jeffrey', last_name='Stewart', email='stewart7222@hotmail.com', email_verified=True, signup_date=datetime.strptime('20180102', '%Y%m%d').strftime('%Y-%m-%d'), referral_count=0, balance=40.58)
# transform the dictionary into a panda series
newseries = pd.Series(newdict)
# name the series 'jefrey'
newseries.name='jefrey'
# append that series to the users dataframe
users = users.append(jefrey)
# get rid of the row 'jeffrey'
users.drop(index='jeffrey', inplace=True)
# Return the whole data frame
users
Mark Chesney
11,747 PointsMark Chesney
11,747 Pointsthank you Putra!! it makes absolute sense!
Shahriyar Ahmed
1,701 PointsShahriyar Ahmed
1,701 PointsRan into the same problem a year later. I used the rename method but didnt include inplace =True. Thank you @Putra Aryotama
Arturo Acosta
7,638 PointsArturo Acosta
7,638 PointsI did this, actually when i check for both results myself i get jefrey and kimberly's last name Deal as the challenge says but somehow the test shows as if i have errors, but for the purpose of the challenge i did update said values