python - Pythonic way to simplify multiply 2 pandas columns with condition -


i looking way how can simplify below examples:

self.df[target_name] = self.df.apply(lambda row: 1 if row['winner'] == 1 , row['winner_over_2_5'] == 1 else 0, axis=1) 

like:

self.df[target_name] = self.df[(self.df.winner == 1)] & self.df[(self.df.winner_over_2_5 == 1)] # not it's not correct

and more complex below

df["profit"] = np.where((df[target_name] == df["predicted"]) & (df["predicted"] == 0),                                   df['match_home'] * df['home_stake'],                                   np.where((dfml[target_name] == df["predicted"]) & (df["predicted"] == 1),                                            df['match_draw'] * df['draw_stake'],                                            np.where((df[target_name] == df["predicted"]) & (df["predicted"] == 2),                                                     df['match_away'] * df['away_stake'],                                                     -0))).astype(float) 

iiuc can use isin:

print df    winner  winner_over_2_5 0       1                0 1       1                1 2       0                2  df['target_name'] = np.where((df.winner.isin([1]) & df.winner_over_2_5.isin([1])),1,0) print df    winner  winner_over_2_5  target_name 0       1                0            0 1       1                1            1 2       0                2            0 

edit (untested, because no data):

df["profit"] = np.where((df[target_name] == df["predicted"]) & (df["predicted"].isin([0])),                                   df['match_home'] * df['home_stake'],                                   np.where((dfml[target_name] == df["predicted"]) & (df["predicted"].isin([1])),                                            df['match_draw'] * df['draw_stake'],                                            np.where((df[target_name] == df["predicted"]) & (df["predicted"].isin([2])),                                                     df['match_away'] * df['away_stake'],                                                     0))).astype(float) 

Comments

Popular posts from this blog

SVG stroke-linecap doesn't work for circles in Firefox? -

routes - Laravel 4 Wildcard Routing to Different Controllers -

cross browser - XSLT namespace-alias Not Working in Firefox or Chrome -