我有一个映射器如下
MAPPER = {
'g': ['gm', 'gram', 'grams', 'gms'],
'ml': ['mls', 'milli-litre', 'mili-litre', 'milli litre', 'mili litre'],
'kg': ['kilo', 'kilo-gram', 'kilo gram', 'kilo grams']
}
和熊猫系列如下
Salt 500 gm
Sugar Powder 500 gm
Sugar 500 gm
Flour 500 gm
Repellent 10 mls
我想将gm和mls更改为映射器中的键,以便结果如下
Salt 500 g
Sugar Powder 500 g
Sugar 500 g
Flour 500 g
Repellent 10 ml
我该怎么做呢?
首先将字典的嵌套列表平铺到具有单词边界的字典,并传递给Series.replace
:
s = s.replace({rf'b{x}b': k for k, v in MAPPER.items() for x in v}, regex=True)
print (s)
0 Salt 500 g
1 Sugar Powder 500 g
2 Sugar 500 g
3 Flour 500 g
4 Repellent 10 ml
Name: a, dtype: object
如果需要替换单元,如果字符串的最后一部分添加$
匹配字符串的结束:
s = s.replace({rf'b{x}b$': k for k, v in MAPPER.items() for x in v}, regex=True)
一种方法:
MAPPER = {
'g': ['gm', 'gram', 'grams', 'gms'],
'ml': ['mls', 'milli-litre', 'mili-litre', 'milli litre', 'mili litre'],
'kg': ['kilo', 'kilo-gram', 'kilo gram', 'kilo grams']
}
lookup = { v : k for k, vs in MAPPER.items() for v in vs }
res = ser.str.replace(rf"b({'|'.join(lookup)})b", lambda x: lookup[x.group()], regex=True)
print(res)
0 Salt 500 g
1 Sugar Powder 500 g
2 Sugar 500 g
3 Flour 500 g
4 Repellent 10 ml
Name: 0, dtype: object