2

I have a pandas dataframe and three lists as follows.

list1 = ['n3', 'n5', 'n7']
list2 = ['n1', 'n2', 'n4', 'n11', 'n12']
list3 = ['n6', 'n8', 'n9', 'n10']

item  n1  n2  n3  n4  n5  n6  n7  n8  n9  n10  n11  n12
item1  1   6   7  8   9   1    6   8   8    9   9    5
item2  1   6   7  6   9   1    8   8   8    9   9    5

I want to select the column names in the three lists and perform the following arithmetic functions.

  • list1: addition
  • list2: take absolute of the number (i.e. abs(n)) and addition
  • list3: take inverse of the number (i.e. 1/n) and addition

For example, if we take item1:

  • list1:add columns n3, n5, n7 i.e. 7+9+6 = 22
  • list2: take abosulte and add columns n1, n2, n4, n11, n12 i.e. abs(1)+abs(6)+abs(8)+abs(9)+abs(5) = 29
  • list3: take inverse and add columns n6, n8, n9, n10 i.e. 1/1 + 1/8 + 1/8 + 1/9 = 1.3611

Now, I want to add the sums separately and total to the dataframe.

item  n1  n2  n3  n4  n5  n6  n7  n8  n9  n10  n11  n12   list1_sum  list2_sum  list3_sum total_sum
item1  1   6   7  8   9   1    6   8   8    9   9    5      xxx  xxx  xxx  xxx
item2  1   6   7  6   9   1    8   8   8    9   9    5      xxx  xxx  xxx  xxx

I was able to do list1 as follows.

df['list1_sum'] = df[list1].sum(axis=1)

However, I could not find how to do the remaining operations.

I am happy to provide more details if needed.

1
  • 1
    Pandas is very handy with arithmetic operations, you are close to the solution. Use df[list2].abs().sum(1) and (1/df[list3]).sum(1) Commented Apr 17, 2019 at 5:26

2 Answers 2

3

Use DataFrame.abs and DataFrame.rdiv for divide from right side:

df['list1_sum'] = df[list1].sum(axis=1)
df['list2_sum'] = df[list2].abs().sum(axis=1)
df['list3_sum'] = df[list3].rdiv(1).sum(axis=1)
#same like 
#df['list3_sum'] = (1 / df[list3]).sum(axis=1)

df['total_sum'] = df[['list1_sum','list2_sum','list3_sum']].sum(axis=1)
print (df)
    item  n1  n2  n3  n4  n5  n6  n7  n8  n9  n10  n11  n12  list1_sum  \
0  item1   1   6   7   8   9   1   6   8   8    9    9    5         22   
1  item2   1   6   7   6   9   1   8   8   8    9    9    5         24   

   list2_sum  list3_sum  total_sum  
0         29   1.361111  52.361111  
1         27   1.361111  52.361111  
Sign up to request clarification or add additional context in comments.

Comments

1

You can also try this:

df[list2].apply(lambda x: 1/x.sum(), axis=1)

df[list2].apply(lambda x: 1.0/x.sum(), axis=1)

However, jezrael's answer is faster

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.