不能替换范围

时间:2018-04-16 09:05:06

标签: pandas replace data-science

下面的代码工作正常,但如果我想替换(30001-35000)显示错误,它会替换特定的范围:

df['Msrp'] = np.where(df['Msrp'].between (25001,30000), 'F', df['Msrp'])
print(df)
df['Msrp'] = np.where(df['Msrp'].between (30001,35000), 'G', df['Msrp'])
print(df)


                    Vin        MakeDescr            SeriesDescr   Msrp
0     2HNYD2H23BH516418            ACURA                    MDX  42580
1     JH4CU2F67AC034248            ACURA                    TSX      F
2     WAUBFAFL3AN022431             AUDI                     A4  32350
3     WBAVC93507K030197              BMW               3 Series  34300
4     1D3HV18P49S803785      DODGE TRUCK     Ram 1500 Pickup-V8  32695
5     2C4RC1BG0CR187071         CHRYSLER      Town & Country-V6      F
  

TypeError:'>''在'str'和'int'

的实例之间不受支持

1 个答案:

答案 0 :(得分:1)

我认为需要numpy.select来替换多个布尔掩码:

df['duration'] = (df['time'] - df['time'].iloc[0]).dt.seconds

print(df)

#                  time  duration
# 0 2014-05-01 18:47:05         0
# 1 2014-05-01 18:47:06         1
# 2 2014-05-02 18:47:08         3
# 3 2014-05-02 18:47:10         5
# 4 2014-05-02 18:47:11         6

您的代码问题是在m1 = df['Msrp'].between (25001,30000) m2 = df['Msrp'].between (30001,35000) df['Msrp'] = np.select([m1, m2], ['F', 'G'], default='not match') 列中np.where获取混合值后的问题 - 数字与Msrp,因此第二个F引发错误。