python - 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'
工作正常。
这个问题有什么好的解决方案?
解决方案
您可以使用pandas.cut
. 需要注意的几点:
- 我们使用 和 的事实排序
dict.keys
是dict.values
一致的。 - 我们明确提供
bins
;labels
注意labels
必须比 少一项bins
。 - 您可能希望为高于 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
推荐阅读
- bootstrap-modal - 未捕获的 RangeError:超出最大调用堆栈大小。在引导模态中,引导多模态
- r - R矩阵值回收?
- pandas - 如何只返回 PANDAS 列中前 5% 的响应
- excel - 我在 excel 中从下面的当前输出中寻找预期的输出
- typescript - 无需嵌套的 TypeScript 类的可理解的 Mixin 链接
- javascript - 使用 JS 命名空间使 Accordion 工作
- javascript - 如何在javascript上定义所选元素的样式
- c - pthread_exit() 和 pthread_join() 不起作用
- codeigniter - 如何使用codeigniter连接到api
- javascript - 如何在 xmlHttpRequest 中发送 csrf 令牌?