Home > database >  with and pmin from R to Python
with and pmin from R to Python

Time:10-19

I have troubles when writing small part of R code into Python. Here is the R code:

W <- expand.grid(list(A = 1:10, C = 1:15))
W$B <- 40 - rowSums(W)

GC <- with(
  W,
  pmin(floor(53*C - 0.9*C^2), pmin(floor(52*B - 1.1*B^2), pmin(62*A, 614)))
)

I need it to rewrite it into Python. This is what I have until now:

import pandas as pd
import itertools


d =  {'A': range(1, 11), 'C': range(1, 16)}

df = pd.DataFrame(itertools.product(*d.values()),columns=d.keys())
df["B"] = 40 - df["A"] - df["C"]

But what is the most pythonic way how to write with function into Python? That is this part:

GC <- with(
  W,
  pmin(floor(53*C - 0.9*C^2), pmin(floor(52*B - 1.1*B^2), pmin(62*A, 614)))
)

Thanks for help.

CodePudding user response:

The equivalent would be assign:

df.assign(B=40 - df['A'] - df['C'])

If you want to have a reference relative to the object itself, use a callable:

df.assign(B=lambda d: 40 - d['A'] - d['C'])

If you want to use a name with special characters or spaces:

df.assign(**{'B': lambda d: 40 - d['A'] - d['C'])})

alternative

you can use eval

df.eval('B = 40-A-C')

minimum of several functions:

df['Gc'] = pd.concat([df.eval('53*C - 0.9*C**2'),
                      df.eval('52*B - 1.1*B**2'),
                      df.eval('62*A').clip(upper=614)],
                     axis=1).min(axis=1)

output:

      A   C   B     Gc
0     1   1  38   52.1
1     1   2  37   62.0
2     1   3  36   62.0
3     1   4  35   62.0
4     1   5  34   62.0
..   ..  ..  ..    ...
145  10  11  19  474.1
146  10  12  18  506.4
147  10  13  17  536.9
148  10  14  16  550.4
149  10  15  15  532.5

[150 rows x 4 columns]
  • Related