文字列を再フォーマットするために私のプログラムのどこかに適用できるヘルパー関数を書く必要があります。ヘルパー関数コードpython
私の第1の機能process_DrugCount(データフレーム)は次のようになり、3つのデータ・フレームを返し:
MemberID DSFS DrugCount
2 61221204 2- 3 months 1
8 30786520 1- 2 months 1
11 28420460 10-11 months 1
私の第2の機能を、replaceMonth(文字列)(例DSFS値を再フォーマットしますヘルパー関数は、「2- 3ヶ月」から「2_3」まで)。 私が持っている以下のコードは、replacemonth()ではなくprocess_DrugCount()でのみこれを実現します。 DrugCount_Y1.replace({'DSFS': {r'(\d+)\s*\-\s*(\d+).*': r'\1_\2'}}, regex=True)
replaceMonth()の下でこれをどのように書き直しますか。ここではすべての私のコードは次のとおりです。
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