簡體   English   中英

使用字典映射數據幀索引

[英]Map dataframe index using dictionary

為什么df.index.map(dict)不能像df['column_name'].map(dict)那樣工作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

喂它一個lambda工作:

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

我沒有回答你的問題......只是給你一個更好的解決方法。
使用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

最后添加get

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

調用map的另一種解決方法:

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轉換為pandas系列。

截至pandas版本0.23.x(2018年5月15日發布),此問題已修復:

import pandas as pd
pd.__version__        # 0.23.4

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.index.map(map_dict)
#        one
# every   10
# good    20
# boy     30
# does    40
# fine    50

從Pandas 0.23.0的What's New頁面中可以看出:

Index.map()現在可以接受系列和字典輸入對象(GH12756,GH18482,GH18509)。

有關更多信息,請查看Index.map的幫助頁面

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

一個較短的替代方案 - 沒有明確調用to_seriespd.Series

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM