本文介绍了助手功能代码python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to write a helper function that can be applied elsewhere in my program to reformat a string.

我的第一个函数process_DrugCount(dataframe)返回三个数据帧,如下所示:

My first function process_DrugCount(dataframe) returns three data frames that look like this:

 MemberID          DSFS  DrugCount
2       61221204   2- 3 months          1
8       30786520   1- 2 months          1
11      28420460  10-11 months          1

我的第二个函数,replaceMonth(string)是一个帮助函数,将重新格式化DSFS值(例如:2-3个月到2_3 )。
以下代码只能在process_DrugCount()中完成,而不是replacemonth()。 DrugCount_Y1.replace({'DSFS':{r'(\d +)\s * \-\s *(\d +)。*':r'\1_\ 2'}},regex = True)
如何在replaceMonth()下重写这个。以下是我的所有代码:

My second function, replaceMonth(string) is a helper function that will reformat DSFS values (example: "2- 3 months" to "2_3"). The following code I have will accomplish this only under process_DrugCount(), not replacemonth(). DrugCount_Y1.replace({'DSFS': {r'(\d+)\s*\-\s*(\d+).*': r'\1_\2'}}, regex=True) How would I rewrite this under replaceMonth(). Here's all my code:

def process_DrugCount(drugcount):
    dc = pd.read_csv("DrugCount.csv")
    sub_map = {'1' : 1, '2':2, '3':3, '4':4, '5':5, '6':6, '7+' : 7}
    dc['DrugCount'] = dc.DrugCount.map(sub_map)
    dc['DrugCount'] = dc.DrugCount.astype(int)
    dc_grouped = dc.groupby(dc.Year, as_index=False)
    DrugCount_Y1 = dc_grouped.get_group('Y1')
    DrugCount_Y2 = dc_grouped.get_group('Y2')
    DrugCount_Y3 = dc_grouped.get_group('Y3')
    DrugCount_Y1.drop('Year', axis=1, inplace=True)
    DrugCount_Y2.drop('Year', axis=1, inplace=True)
    DrugCount_Y3.drop('Year', axis=1, inplace=True)
    print DrugCount_Y1
    a = DrugCount_Y1.replace({'DSFS': {r'(\d+)\s*\-\s*(\d+).*': r'\1_\2'}}, regex=True) #WORKS HERE!
    return (DrugCount_Y1,DrugCount_Y2,DrugCount_Y3)

# this function converts strings such as "1- 2 month" to "1_2"
def replaceMonth(string):
    string.replace({'DSFS': {r'(\d+)\s*\-\s*(\d+).*': r'\1_\2'}}, regex=True) #Doesn't change dash to underscore. 
    return a_new_string


推荐答案

。也许我没有问这个问题。
我需要做的是这样的:

it was easier than that. Maybe I didn't ask the question right. All I needed to do was this:

def replaceMonth(string):
replace_map = {'0-1 2,3〜4个月:3〜4,4〜5个月,4〜5 5-6个月:5_6,6-7个月:6_7,\
7- 8个月:7_8,8- 9个月:8_9 ,9-10个月:9_10,10-11个月:10_11,11-12个月:11_12}
a_new_string = string.map(replace_map)
返回a_new_string

只需重命名列名。

这篇关于助手功能代码python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 00:41