我想要替换某个范围内的值为其他值。
我有一个包含字符作为键和上限范围作为值的字典,如下所示 -
我已经写了以下代码:
这段代码显示了一个错误:
然而,这行代码
有什么好的解决方案吗?
我有一个包含字符作为键和上限范围作为值的字典,如下所示 -
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'
却能够正常运行。有什么好的解决方案吗?
data['my_col']
的数据类型是str
吗?尝试使用data['my_col'],astype('int32').between(k,j)
。 - wwii