python-3.x 忽略不打算使用Map函数Map的Pandas Dataframe 索引

tag5nh1u  于 2022-12-15  发布在  Python
关注(0)|答案(5)|浏览(102)

我有以下 Dataframe

index,name,score,attempts,qualify
a,Anastasia,12.5,1,yes
b,Dima,9.0,3,no
c,Katherine,16.5,2,yes
d,James,NaN,3,no
e,Emily,9.0,2,no

字符串
我正在尝试使用PandasMap函数来更新名称列,其中名称是詹姆斯或艾米丽的任何测试值99。

codes = {'James':'99','Emily':'99'}
dff['name'] = dff['name'].map(codes)
dff

我得到了以下输出-

index,name,score,attempts,qualify
a,NaN,12.5,1,yes
b,NaN,9.0,3,no
c,NaN,16.5,2,yes
d,99,NaN,3,no
e,99,9.0,2,no

注意,name列值James和艾米丽已经更新为99,但是name的其余值Map为NaN。我们如何忽略不打算Map的索引呢?

qaxu7uf2

qaxu7uf21#

问题是map函数会将字典值应用于'name'列中的所有值,而不仅仅是指定的值。要解决这个问题,可以使用replace方法:

dff['name'] = dff['name'].replace({'James':'99','Emily':'99'})

这将仅替换指定的值,而其他值保持不变。

suzh9iv8

suzh9iv82#

我相信您可能正在寻找replace而不是map

import pandas as pd
names = pd.Series([
    "Anastasia",
    "Dima",
    "Katherine",
    "James",
    "Emily"
])

names.replace({"James": "99", "Emily": "99"})

 
# 0    Anastasia
# 1         Dima
# 2    Katherine
# 3           99
# 4           99
# dtype: object

如果您真的打算使用map,那么您必须提供一个知道如何处理它可能遇到的每个名称的函数。

codes = {"James": "99", "Emily": "99"}

# If the lookup into `code` fails,
# return the name that was used for lookup
names.map(lambda name: codes.get(name, name))
t98cgbkg

t98cgbkg3#

codes = {'James':'99',
         'Emily':'99'}
dff['name'] = dff['name'].replace(codes)
dff

replace()满足以下要求-

index,name,score,attempts,qualify
a,Anastasia,12.5,1,yes
b,Dima,9.0,3,no
c,Katherine,16.5,2,yes
d,99,NaN,3,no
e,99,9.0,2,no
ejk8hzay

ejk8hzay4#

你可以用一种方法来实现它

dff['name'] = dff['name'].map(codes).fillna(dff['name'])
628mspwn

628mspwn5#

codes = {'James':'99','Emily':'99'}
dff['name'] = dff['name'].map(codes).fillna(dff['name'])

dff

index   name        score   attempts    qualify
0   a       Anastasia   12.5    1           yes
1   b       Dima        9.0     3           no
2   c       Katherine   16.5    2           yes
3   d       99          NaN     3           no
4   e       99          9.0     2           no

相关问题