我需要编写一个助手函数,可以应用到我的程序的其他地方,以重新格式化字符串。在
我的第一个函数process_DrugCount(dataframe)返回三个数据帧,如下所示:
MemberID DSFS DrugCount
2 61221204 2- 3 months 1
8 30786520 1- 2 months 1
11 28420460 10-11 months 1
我的第二个函数replaceMonth(string)是一个helper函数,它将重新格式化DSFS值(例如:“2-3个月”到“2\u3”)。
下面的代码只能在process\u DrugCount()下完成,而不是replacemonth()。DrugCount_Y1.replace({'DSFS': {r'(\d+)\s*\-\s*(\d+).*': r'\1_\2'}}, regex=True)
我如何在replaceMonth()下重写它。这是我所有的代码:
比那容易多了。也许我没问对问题。 我要做的就是:
def replaceMonth(string): replace_map = {'0- 1 month' : "0_1", "1- 2 months": "1_2", "2- 3 months": "2_3", "3- 4 months": '3_4', "4- 5 months": "4_5", "5- 6 months": "5_6", "6- 7 months": "6_7", \ "7- 8 months" : "7_8", "8- 9 months": "8_9", "9-10 months": "9_10", "10-11 months": "10_11", "11-12 months": "11_12"} a_new_string = string.map(replace_map) return a_new_string
只是重命名列名。在
实际上,您不需要为此使用特殊函数,因为它已经存在-replace():
相关问题 更多 >
编程相关推荐