Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update elements of dataframe by applying function involving same row elements

Tags:

python

pandas

I have the following dataframe:

a    b    c    d    e    f    g    h    i    j
1    2    3    4    5    6    7    8   0.1  0.11
11   12   13   14   15   16   17   18  0.2  0.12
21   22   23   24   25   26   27   28  0.3  0.13
31   32   33   34   35   36   37   38  0.4  0.14

I want to read EACH ROW and for each value in columns a to h (in that row), subtract value in column i and divide by value in column j and to replace that original value with this resultant value And to update the whole dataframe (from columns a to h).

How should I proceed in this case?

like image 528
MNK Avatar asked May 14 '19 21:05

MNK


2 Answers

You can use reshape columns i and j and subtract,

df = df.iloc[:, :8].sub(df['i'].values[:, None]).div(df['j'].values[:, None]).round(2)

    a       b       c       d       e       f       g       h
0   8.18    17.27   26.36   35.45   44.55   53.64   62.73   71.82
1   90.00   98.33   106.67  115.00  123.33  131.67  140.00  148.33
2   159.23  166.92  174.62  182.31  190.00  197.69  205.38  213.08
3   218.57  225.71  232.86  240.00  247.14  254.29  261.43  268.57
like image 68
Vaishali Avatar answered Oct 05 '22 16:10

Vaishali


Make use of filter and the underlying numpy arrays.

u = df.filter(regex='[^ij]')

res = (u.values - df.i.values[:, None]) / df.j.values[:, None]

pd.DataFrame(res, columns=u.columns)

            a           b           c           d           e           f           g           h
0    8.181818   17.272727   26.363636   35.454545   44.545455   53.636364   62.727273   71.818182
1   90.000000   98.333333  106.666667  115.000000  123.333333  131.666667  140.000000  148.333333
2  159.230769  166.923077  174.615385  182.307692  190.000000  197.692308  205.384615  213.076923
3  218.571429  225.714286  232.857143  240.000000  247.142857  254.285714  261.428571  268.571429
like image 23
user3483203 Avatar answered Oct 05 '22 16:10

user3483203