将十进制转换为罗马数字 [英] Convert decimal to Roman numerals
问题描述
d_hsp={"1":"I","2":"II","3":"III","4":"IV","5":"V","6":"VI","7":"VII","8":"VIII",
"9":"IX","10":"X","11":"XI","12":"XII","13":"XIII","14":"XIV","15":"XV",
"16":"XVI","17":"XVII","18":"XVIII","19":"XIX","20":"XX","21":"XXI",
"22":"XXII","23":"XXIII","24":"XXIV","25":"XXV"}
HSP_OLD['tryl'] = HSP_OLD['tryl'].replace(d_hsp, regex=True)
HSP_OLD
是一个数据帧,tryl
是HSP_OLD
的一列,这是tryl
中值的一些示例:
HSP_OLD
is a dataframe, tryl
is one column of HSP_OLD
, and here's some example of values in tryl
:
SAF/HSP: Secondary diagnosis E code 1
SAF/HSP: Secondary diagnosis E code 11
我使用字典进行替换,它适用于1-10,但对于11,它将变为"II",对于12,它将变为"III".
I use a dictionary to replace, it works for 1-10, but for 11, it will become "II" , for 12, it will become "III".
推荐答案
您需要保持项目的顺序,并从最长的子字符串开始搜索.
You need to keep the order of the items, and start searching with the longest substring.
您可以在此处使用OrderDict
.要初始化它,请使用元组列表.初始化时,您可以在此处将其反转,但是以后也可以进行.
You may use an OrderDict
here. To initialize it, use a list of tuples. You may reverse it already here, when initializing, but you can do it later, too.
import collections
import pandas as pd
# My test data
HSP_OLD = pd.DataFrame({'tryl':['1. Text', '11. New Text', '25. More here']})
d_hsp_lst=[("1","I"),("2","II"),("3","III"),("4","IV"),("5","V"),("6","VI"),("7","VII"),("8","VIII"), ("9","IX"),("10","X"),("11","XI"),("12","XII"),("13","XIII"),("14","XIV"),("15","XV"), ("16","XVI"),("17","XVII"),("18","XVIII"),("19","XIX"),("20","XX"),("21","XXI"), ("22","XXII"),("23","XXIII"),("24","XXIV"),("25","XXV")]
d_hsp = collections.OrderedDict(d_hsp_lst) # Creating the OrderedDict
d_hsp = collections.OrderedDict(reversed(d_hsp.items())) # Here, reversing
>>> HSP_OLD['tryl'] = HSP_OLD['tryl'].replace(d_hsp, regex=True)
>>> HSP_OLD
tryl
0 I. Text
1 XI. New Text
2 XXV. More here
这篇关于将十进制转换为罗马数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!