Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map dataframe index using dictionary

Tags:

python

pandas

Why doesn't df.index.map(dict) work like df['column_name'].map(dict)?

Here's a little example of trying to use index.map:

import pandas as pd  df = pd.DataFrame({'one': {'A': 10, 'B': 20, 'C': 30, 'D': 40, 'E': 50}}) map_dict = {'A': 'every', 'B': 'good', 'C': 'boy', 'D': 'does', 'E': 'fine'} df '''     one A   10 B   20 C   30 D   40 E   50 '''  df['two'] = df.index.map(mapper=map_dict) 

This raises TypeError: 'dict' object is not callable

Feeding it a lambda works:

df['two'] = df.index.map(mapper=(lambda x: map_dict[x])); df '''    one    two A   10  every B   20   good C   30    boy D   40   does E   50   fine ''' 

However, resetting the index and mapping on a column works as expected without complaint:

df.reset_index(inplace=True) df.rename(columns={'index': 'old_ndx'}, inplace=True) #so there's no index name confusion df['two'] = df.old_ndx.map(map_dict); df  '''   old_ndx  one    two 0       A   10  every 1       B   20   good 2       C   30    boy 3       D   40   does 4       E   50   fine ''' 
like image 814
cfort Avatar asked Apr 11 '17 21:04

cfort


People also ask

How do you map an index in Python?

To get access to the index in the map function:Use the enumerate() function to get an object of index/item tuples. Unpack the index and item values in the function you pass to map() . The function will get passed a tuple containing the index and item on each iteration.

How do I apply a map to a DataFrame column?

apply() is used to apply a function along an axis of the DataFrame or on values of Series. applymap() is used to apply a function to a DataFrame elementwise. map() is used to substitute each value in a Series with another value.

How do I change the index of a data frame?

To reset the index in pandas, you simply need to chain the function . reset_index() with the dataframe object. On applying the . reset_index() function, the index gets shifted to the dataframe as a separate column.


2 Answers

I'm not answering your question... Just giving you a better work around.
Use to_series() them map

df = pd.DataFrame({'one': {'A': 10, 'B': 20, 'C': 30, 'D': 40, 'E': 50}}) map_dict = {'A': 'every', 'B': 'good', 'C': 'boy', 'D': 'does', 'E': 'fine'}  df['two'] = df.index.to_series().map(map_dict)  df     one    two A   10  every B   20   good C   30    boy D   40   does E   50   fine 
like image 177
piRSquared Avatar answered Sep 18 '22 03:09

piRSquared


Adding get at the end

df['Two']=df.index.map(map_dict.get) df Out[155]:     one    Two A   10  every B   20   good C   30    boy D   40   does E   50   fine 
like image 38
BENY Avatar answered Sep 20 '22 03:09

BENY