Python 熊猫:如何用字符串替换范围中的值?
我试图用其他值替换某个范围内的值 我有一个字典,包含一个字符作为键,上限作为值,如下所示-Python 熊猫:如何用字符串替换范围中的值?,python,python-3.x,pandas,dataframe,Python,Python 3.x,Pandas,Dataframe,我试图用其他值替换某个范围内的值 我有一个字典,包含一个字符作为键,上限作为值,如下所示- replace_dict = { 'A': 10, 'B': 21, 'C': 34, 'D': 49, 'E': 66, 'F': 85, 'G': 107, 'H': 132, 'I': 160, 'J': 192,
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:“>=”在“str”和“int”的实例之间不受支持。
但是,(1,10)之间的行data.loc[data['my_col']='A'
工作正常
对于这个问题,什么是好的解决方案?您可以使用所需的范围和
map
使用intervalIndex
设置
map
使用您的intervalIndex
ranges = pd.DataFrame(replace_dict, index=['STOP']).T.reset_index()
ranges['START'] = (ranges.STOP.shift(1)+1).fillna(1)
ranges.index = pd.IntervalIndex.from_arrays(ranges.START, ranges.STOP, closed='both')
index STOP START
[1.0, 10.0] A 10 1.0
[11.0, 21.0] B 21 11.0
[22.0, 34.0] C 34 22.0
[35.0, 49.0] D 49 35.0
[50.0, 66.0] E 66 50.0
etc...
df = pd.DataFrame({'nums': np.random.randint(1, 1000, 10)})
nums
0 699
1 133
2 829
3 299
4 306
5 691
6 172
7 225
8 522
9 671
df.nums.map(ranges['index'])
0 Q
1 I
2 R
3 M
4 M
5 Q
6 J
7 K
8 P
9 Q
你可以用。需要注意的几点:
dict.keys
和dict.values
的事实顺序是一致的箱子
和标签
;请注意,标签
必须比箱子少一项
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
只需反转i和jIs
数据['my_col']
的数据类型str
?尝试data['my_col',astype('int32')。介于(k,j)