gpt4 book ai didi

python - 辅助函数代码python

转载 作者:行者123 更新时间:2023-11-28 19:13:37 24 4
gpt4 key购买 nike

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

我的第一个函数 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) 是一个辅助函数,它将重新格式化 DSFS 值(例如:“2- 3 个月”到“2_3”)。我的以下代码将仅在 process_DrugCount() 下完成此操作,而不是 replacemonth()。 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

最佳答案

实际上你不需要特殊的功能,因为它已经存在 - 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

关于python - 辅助函数代码python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36439359/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com