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, n7i.e.7+9+6 = 22 - list2:
take abosulte and add columns n1, n2, n4, n11, n12i.e.abs(1)+abs(6)+abs(8)+abs(9)+abs(5) = 29 - list3:
take inverse and add columns n6, n8, n9, n10i.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.
df[list2].abs().sum(1)and(1/df[list3]).sum(1)