Converting working code into a method, which will take dataframe columns values as input and would return 0 and 1 as values of a new column

Viewed 22

I am new to core python. I have a working code which I need to convert into a method. So, I have around 50k data with 30 columns. Out of 30 columns 3 columns are important for this requirement. Id,Code, and bill_id. I need to populate new column "multiple_instance" with 0s and 1s. Hence, final dataframe will contain 50k data with 31 columns. 'Code' column contains n number of codes, hence I am filtering my interest of codes and applying the remaining concept. I need to pass these 3 columns in a method() which would return 0s and 1s.

Note: multiple_instance_codes is a variable which can be changed later.

multiple_instance_codes = ['A','B','C','D']
filt = df['Code'].str.contains('|'.join(multiple_instance_codes ), na=False,case=False)
df_mul = df[filt]
df_temp = df_mul.groupby(['Id'])[['Code']].size().reset_index(name='count')
df_mul = df_mul.merge(df_temp, on='Id', how='left')
df_mul['Cumulative_Sum'] = df_mul.groupby(['bill_id'])['count'].apply(lambda x: x.cumsum())
df_mul['multiple_instance'] = np.where(df_mul['Cumulative_Sum'] > 1, 1, 0)```

**Sample data :**
bill_id     Id   Code       Cumulative_Sum   multiple_instance
10          1    B          1                0
10          2    A          2                1
10          3    C          3                1
10          4    A          4                1


1 Answers

Nevermind, It is completed and working fine. def multiple_instance(df): df_scored = df.copy() filt = df_scored['Code'].str.contains('|'.join(multiple_instance_codes), na=False,case=False) df1 = df_scored[filt] df_temp = df1.groupby(['Id'])[['Code']].size().reset_index(name='count') df1 = df1.merge(df_temp, on='Id', how='left') df1['Cum_sum'] = df1.groupby(['bill_id'])['count'].apply(lambda x: x.cumsum()) df_scored = df_scored.merge(df1) df_scored['muliple instance'] = np.where(df_scored['Cumulative_Sum'] > 1, 1, 0) return df_scored

Related