Python Forum
How to sum across variable columns in a dataframe
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to sum across variable columns in a dataframe
#2
Hi Rennerom

That's a tricky one, maybe try apply:

import pandas as pd
from numpy import arange


data = {'ID': ['a','b','c','d','e'], 
        'Target': [2,4,1,2,5], 
        'P1': [30,50,22.2,1,24.4], 
        'P2':[40,66.34,33,5,8], 
        'P3':[59,100,41,6,30], 
        'P4':[35,130.22,12,0,21], 
        'P5':[22,90,10.5,1.1,19.9]
        }
 
df = pd.DataFrame(data)
df['Sum']=df.iloc[:,2:].sum(axis=1)
df["varsum"]=df.apply(lambda row: row[["P"+str(i) for i in arange(1,1+row["Target"])]].sum(), axis=1)
print(df)

  ID  Target    P1     P2   P3      P4    P5     Sum  varsum
0  a       2  30.0  40.00   59   35.00  22.0  186.00   70.00
1  b       4  50.0  66.34  100  130.22  90.0  436.56  346.56
2  c       1  22.2  33.00   41   12.00  10.5  118.70   22.20
3  d       2   1.0   5.00    6    0.00   1.1   13.10    6.00
4  e       5  24.4   8.00   30   21.00  19.9  103.30  103.30
Reply


Messages In This Thread
RE: How to sum across variable columns in a dataframe - by nealc - Jan-28-2021, 07:08 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Converting a json file to a dataframe with rows and columns eyavuz21 13 4,174 Jan-29-2023, 03:59 PM
Last Post: eyavuz21
  Nested for loops: Iterating over columns of a DataFrame to plot on subplots dm222 0 1,641 Aug-19-2022, 11:07 AM
Last Post: dm222
  Apply fillna to multiple columns in dataframe rraillon 2 2,372 Aug-05-2021, 01:11 PM
Last Post: rraillon
  How to rename dataframe columns based on the content in an index? ar_mahdavi 2 2,432 Jun-07-2021, 06:09 AM
Last Post: ricslato
  How to split dataframe object rows to columns Mekala 1 2,441 Nov-12-2020, 04:18 PM
Last Post: michael1789
  convert list to five columns dataframe in sequence tonycat 2 2,433 Sep-29-2020, 06:47 AM
Last Post: tonycat
  How to melt dataframe multiple columns to one column Mekala 1 2,828 Sep-24-2020, 08:32 PM
Last Post: scidam
  Concatenate two files with different columns into one dataframe moralear27 1 2,093 Sep-11-2020, 10:18 PM
Last Post: moralear27
  How to map dataframe based on two columns Mekala 0 6,178 Aug-29-2020, 07:36 AM
Last Post: Mekala
  Cmparing columns in dataframe Rejoice 0 1,390 Aug-17-2020, 08:48 PM
Last Post: Rejoice

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020