大熊猫的条件替换

hme*_*erg 9 python conditional replace pandas

我有一个跨越数年的数据框,在某些时候他们改变了种族代码.所以我需要重新编码以年为条件的值 - 这是同一数据帧中的另一列.例如1到3,2到3,3到4等等:

old = [1, 2, 3, 4, 5, 91]
new = [3, 3, 4, 2, 1, 6]
Run Code Online (Sandbox Code Playgroud)

这只是在1996年至2001年期间完成的.同一栏(种族)中其他年份的价值不得改变.希望避免太多低效的循环,我试过:

    recode_years = range(1996,2002)
    for year in recode_years:
        df['ethnicity'][df.year==year].replace(old, new, inplace=True)
Run Code Online (Sandbox Code Playgroud)

但是数据框中的原始值没有改变.替换方法本身已替换并正确返回新值,但inplace选项似乎不会在应用条件时影响原始数据帧.这对于经验丰富的Pandas用户来说可能是显而易见的,但肯定必须有一些简单的方法来实现这一点,而不是循环遍历每个singel元素?

编辑(x2):她是另一种方法的例子,它也没有用('替换长度必须等于系列长度'和"TypeError:数组不能安全地转换为所需类型"):

oldNewMap = {1:2, 2:3}
df2 = DataFrame({"year":[2000,2000,2000,2001,2001,2001],"ethnicity":[1,2,1,2,3,1]})
df2['ethnicity'][df2.year==2000] = df2['ethnicity'][df2.year==2000].map(oldNewMap)
Run Code Online (Sandbox Code Playgroud)

编辑:这似乎是特定于安装/版本的问题,因为这在我的其他计算机上工作正常.

Bre*_*arn 10

以不同的方式做它可能更简单:

oldNewMap = {1: 3, 2: 3, 3: 4, 4: 2, 5: 1, 91: 6}
df['ethnicity'][df.year==year] = df['ethnicity'][df.year==year].map(oldNewMap)
Run Code Online (Sandbox Code Playgroud)