帮助函数代码python

2024-09-30 18:19:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要编写一个助手函数,可以应用到我的程序的其他地方,以重新格式化字符串。在

我的第一个函数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()下重写它。这是我所有的代码:

^{pr2}$

Tags: 数据函数字符串代码程序dataframestring地方
2条回答

比那容易多了。也许我没问对问题。 我要做的就是:

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()

In [32]: replacements = {
   ....:     'DSFS': {
   ....:         r'(\d+)\s*\-\s*(\d+).*': r'\1_\2'
   ....:     },
   ....:     'DrugCount': {
   ....:         r'\+': ''
   ....:     }
   ....: }

In [33]: dc
Out[33]:
   MemberID Year         DSFS DrugCount
0  48925661   Y2  9-10 months        7+
1  90764620   Y3  8- 9 months         3
2  61221204   Y1  2- 3 months         1

In [34]: dc.replace(replacements, regex=True, inplace=True)

In [35]: dc['DrugCount'] = dc.DrugCount.astype(int)

In [36]: dc
Out[36]:
   MemberID Year  DSFS  DrugCount
0  48925661   Y2  9_10          7
1  90764620   Y3   8_9          3
2  61221204   Y1   2_3          1

In [37]: dc.dtypes
Out[37]:
MemberID      int64
Year         object
DSFS         object
DrugCount     int32
dtype: object

相关问题 更多 >