Home > Software engineering >  How to expit transfration to a pandas dataframe
How to expit transfration to a pandas dataframe

Time:07-01

Here's my dataset

Id      B       C      
1       0      -1
2       2      -2

here's the expit transformation (exp(x)/(1 exp(x)))

Id     B               C      
1      0.5         0.269
2      0.881       0.119

CodePudding user response:

Use vectorization:

import numpy as np

df.iloc[:, 1:] = np.exp(df.iloc[:, 1:])/(1 np.exp(df.iloc[:, 1:]))
print(df)

# Output:
   Id         B         C
0   1  0.500000  0.268941
1   2  0.880797  0.119203

You can also define your columns explicitly:

cols = ['B', 'C']
df[cols] = np.exp(df[cols])/(1 np.exp(df[cols]))

CodePudding user response:

As you said, this transformation is sometimes called an Expit, and SciPy has a specific function for calculating it.

from scipy.special import expit

cols = ['B', 'C']
df[cols] = expit(df[cols])
print(df)

Output:

   Id         B         C
0   1  0.500000  0.268941
1   2  0.880797  0.119203

Using numpy we can still simplify the equation a bit:

df[cols] = 1/(1 np.exp(-df[cols]))
print(df)

Output:

   Id         B         C
0   1  0.500000  0.268941
1   2  0.880797  0.119203

CodePudding user response:

You could apply the apply function as follows:

import pandas as pd
import numpy as np

df = pd.DataFrame.from_dict(data={"B": [0,2], "C": [-1,-2]})
#    B  C
# 0  0 -1
# 1  2 -2

df.apply(lambda x: np.exp(x)/(1 np.exp(x)))
#           B         C
# 0  0.500000  0.268941
# 1  0.880797  0.119203
  • Related