FunnyChef
FunnyChef

Reputation: 1946

Update pandas DataFrame based on index

I have the following DataFrame:

df = pd.DataFrame(index=['A','B','C'], columns=['x','y'])

     x    y
A  NaN  NaN
B  NaN  NaN
C  NaN  NaN

I need to update column 'x' based on matching the index value to the following dictionary:

my_dict = {'A': "map_1", 'B': "map_2", "c": "map_3"}

So, the end result should be;

     x     y
A  map_1  NaN
B  map_2  NaN
C  map_3  NaN

I know how to use the map function if I was comparing another column, but I need to compare the index.

Upvotes: 2

Views: 42

Answers (1)

Scott Boston
Scott Boston

Reputation: 153460

Try this:

df['x'] = df.index.map(my_dict)

Output: Note the typo on my_dict small c instead of C.

       x    y
A  map_1  NaN
B  map_2  NaN
C    NaN  NaN

Upvotes: 1

Related Questions