Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operations with different parts of the same dataframe

Assume there is a dataframe:

    kind  value
0      1      1
1      1      2
2      1      3
3      1      4
4      1      5
5      2      6
6      2      7
7      2      8
8      2      9
9      2      10

We can do something with a filtered part of a dataframe:

df.loc[df['kind']==1, 'value'] = df.loc[df['kind']==1, 'value'] * 2

How to perform a calculation involving two or more parts of the same dataframe, assuming their size is equal? Something like this:

df.loc[df['kind']==1, 'value'] = 
    df.loc[df['kind']==1, 'value'] * df.loc[df['kind']==2, 'value']

(this doesn't work)

like image 472
Michael Avatar asked Dec 09 '25 06:12

Michael


2 Answers

Try this:

In [107]: df.loc[df['kind']==1, 'value'] *= df.loc[df['kind']==2, 'value'].values

In [108]: df
Out[108]:
   kind  value
0     1      6
1     1     14
2     1     24
3     1     36
4     1     50
5     2      6
6     2      7
7     2      8
8     2      9
9     2     10
like image 88
MaxU - stop WAR against UA Avatar answered Dec 11 '25 20:12

MaxU - stop WAR against UA


Use:

m = df['kind']==1
df.loc[m, 'value'] = df.loc[m, 'value'].values * df.loc[df['kind']==2, 'value'].values
print (df)
   kind  value
0     1      6
1     1     14
2     1     24
3     1     36
4     1     50
5     2      6
6     2      7
7     2      8
8     2      9
9     2     10
like image 35
jezrael Avatar answered Dec 11 '25 20:12

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!