使用字典映射数据框索引 [英] Map dataframe index using dictionary

查看:73
本文介绍了使用字典映射数据框索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么df.index.map(dict)不能像df['column_name'].map(dict)一样工作?

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

这是尝试使用index.map的一个小例子:

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)

这引起了TypeError: 'dict' object is not callable

给它输入一个lambda可以起作用:

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

推荐答案

我没有回答您的问题...只是为您提供了更好的解决方法.
使用to_series()他们map

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

这篇关于使用字典映射数据框索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆