首页 > 解决方案 > Pandas:如何用字符串替换范围内的值?

问题描述

我正在尝试用其他值替换某个范围内的值。

我有一个字典,其中包含一个 char 作为键,上限作为一个值,如下所示 -

replace_dict = {
        'A': 10, 
        'B': 21, 
        'C': 34, 
        'D': 49, 
        'E': 66, 
        'F': 85, 
        'G': 107, 
        'H': 132, 
        'I': 160, 
        'J': 192, 
        'K': 229, 
        'L': 271, 
        'M': 319, 
        'N': 395, 
        'O': 495, 
        'P': 595, 
        'Q': 795, 
        'R': 1100
}

我需要用范围内的相应键替换这些值。

例如:

Values in the range of 1-10 will be replaced by 'A',
Values in the range of 11-21 will be replaced by 'B'
Values in the range of 22-34 will be replaced by 'C'
Values in the range of 35-50 will be replaced by 'D'
Values in the range of 51-66 will be replaced by 'E'

我编写了以下代码:

k=1
for i, j in replace_dict.items():
    data.loc[data['my_col'].between(k,j)] = i
    k=j+1

此代码显示TypeError: '>=' not supported between instances of 'str' and 'int'.

但是,这条线data.loc[data['my_col'].between(1,10)] = 'A'工作正常。

这个问题有什么好的解决方案?

标签: pythonpython-3.xpandasdataframe

解决方案


您可以使用pandas.cut. 需要注意的几点:

  1. 我们使用 和 的事实排序dict.keysdict.values一致的。
  2. 我们明确提供binslabels注意labels必须比 少一项bins
  3. 您可能希望为高于 1100 的值添加一个额外的 bin。

这是一个最小的例子。

df = pd.DataFrame({'col': [500, 123, 56, 12, 1000, 2, 456]})

df['mapped'] = pd.cut(df['col'],
                      bins=[1]+list(replace_dict.values()),
                      labels=list(replace_dict.keys()))

print(df)

    col mapped
0   500      P
1   123      H
2    56      E
3    12      B
4  1000      R
5     2      A
6   456      O

推荐阅读