I have two dataframes:

    id   exerciseId  sets
    1       1         12  
    2       1         14
    2       2         15
    2       2         15

    id   exerciseName
    1      Squat        
    2      Pullup

I would like to find a way to replace the exerciseId in self.thisSession_df with the corresponding name from self.exercises_df

Hopeful result:

    id   exerciseId    sets
    1       Squat       12  
    2       Squat       14
    2       Pullup      15
    2       Pullup      15

I tried a solution that I found on here and modified it to come up with: self.thisSession_df['exerciseId'] = self.thisSession_df['exerciseId'].map(df1.set_index('id')['exerciseName'])

This gives me error: string indices must be integers

I would appreciate a nudge in right direction!


I would recommend merging your two dataframes to get the exercise names:

exercise_name_df = thisSession_df.merge(exercises_df, left_on='exerciseId', right_on='id')

This will give you a dataframe like

    id   exerciseId  sets  exerciseName
    1       1         12      Squat
    2       1         14      Squat
    2       2         15     Pullup
    2       2         15     Pullup

Then you can replace exerciseId with the name if you really want to:

# reassign id to name
exercise_name_df['exerciseId'] = exercise_name_df['exerciseName']
# drop redundant column
exercise_name_df.drop(columns=['exerciseName'], inplace=True)

I would argue that the above method is more readable than the map() solution. But I think the map() solution should also work with a small tweak:

thisSession_df['exerciseId'] = thisSession_df['exerciseId'].map(exercises_df.set_index('id')['exerciseName'])
|improve this answer|||||
  • $\begingroup$ Yes, thank you so much! $\endgroup$ – Jacob Dec 11 '19 at 18:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.