Display Data Data Index Using Dictionary

Why df.index.map (dict) does not work as df ['column_name']. map (dict)?

Here is a small example using 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 a TypeError: 'dict' object is not callable

Feeding it with lambdas:

 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 displaying in a column works without expectations:

 df.reset_index(inplace=True) df.rename(columns={'index': 'old_ndx'}, inplace=True) #so there 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 ''' 
+5
source share
5 answers

I do not answer your question ... Just giving you the best job.
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 
+7
source

Alternative workaround for calling a card:

 df['two'] = pd.Series(map_dict) df one two A 10 every B 20 good C 30 boy D 40 does E 50 fine 

In any case, until the display problem is resolved (for juanpa.arrivillaga comment), you need to convert the index or map binding file to the pandas series.

+5
source

Adding get to 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 
+5
source

map (the python keyword) seems to be used as the df.index method

Since this has its own internal requirements, passing its argument, which does not have the __call__ method, is not allowed.

lambda and functions can be called, a simple test:

 def foo(): pass if foo.__call__: print True # Prints True bar = lambda x: x+1 if bar.__call__: print True # Prints True print {'1':'one'}.__call__ # AttributeError: 'dict' object has no attribute '__call__' 
0
source

A shorter alternative is without explicitly calling to_series or pd.Series :

 df['two'] = df.rename(map_dict).index 
0
source

Source: https://habr.com/ru/post/1266610/


All Articles