2017-04-11 33 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