2017-04-11 61 views
4

为什么df.index.map(dict)不像df ['column_name']。map(dict)?使用字典映射数据帧索引

这里是试图用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) 

这就提出了TypeError: 'dict' object is not callable

喂养它拉姆达作品:

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 
''' 

然而,重置索引和映射在列上按预期工作,无需投诉:

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 
''' 
+2

添加get根据[该文档](HTTP://pandas.pydata .org/pandas-docs/version/0.18.1/generated/pandas.Index.map.html),'pandas.Index.map'需要可调用。你的问题*为什么*是做出这个设计决定的? –

+2

[这里](https://github.com/pandas-dev/pandas/issues/12756)是一个相关的问题。它似乎只是在裂缝中滑过,他们没有得到修理。它似乎是[目前正在补救](https://github.com/pandas-dev/pandas/pull/15081)。 –

回答

5

我不会回答你的问题......只是给你身边的一个更好的工作。
使用to_series()他们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 
0

map(一个python关键字)显然被用作df.index

由于这种有其自己的内部的要求,将其传递不具有__call__方法是不允许的参数的方法。

lambda和功能调用,一个简单的测试:

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__' 
+1

'map'没有被“覆盖”。 'map'是一个函数,而不是一个方法,所以没有什么可以重载。 –

5

另一种解决方法调用地图:

df['two'] = pd.Series(map_dict) 

df 

    one two 
A 10 every 
B 20 good 
C 30 boy 
D 40 does 
E 50 fine 

在任何情况下,直到映射问题得到解决(每juanpa.arrivillaga的评论),你必须转换要么索引或dict-to-map到熊猫系列。

0

较短的替代--with没有显式地调用to_seriespd.Series

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

在端

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