Proj_Com_Sum comp_1 comp_2 comp_3 Proj_Val_sum val_1 val_2 val_3
70 10 20 35 67 20 30 15
100 50 30 25 70 25 30 15
Run Code Online (Sandbox Code Playgroud)
Given the above as Pandas DataFrame df, I would like to add a Colunm Com_total , Val_total , Proj_Tot_Diff
Where
Com_total = comp_1 + comp_2 + comp_3
Val_total = val_1 + val_2 + val_3
Proj_Tot_Diff = Com_total - Proj_Com_Sum
Run Code Online (Sandbox Code Playgroud)
Since I have about comp .. it would be a long code to write
Com_total = comp_1 + comp_2 + comp_3 .. comp_58
Run Code Online (Sandbox Code Playgroud)
Please Note comp_1..comp_2 may not follow a regex pattern. it could be some State Names like Florida, NY, etc. All we know is 2nd colunm to 58th column are to be added.
Hence, I want Some code like
df['Com_total']= df[ col 2:58 ].sum
# Whats the correct Syntax
Run Code Online (Sandbox Code Playgroud)
How to Specify the In Between Columns in a precise notation. Please help with correct Syntax
You can using slicing if your column headers are ordered properly, however it safer if you use @piRSquared's method using filter:
df['Com_total'] = df.loc[:,'comp_1':'comp_3'].sum(1)
df['Val_total'] = df.loc[:,'val_1':'val_3'].sum(1)
df['Proj_Tot_diff'] = df['Com_total'] - df['Proj_Com_Sum']
print(df)
Run Code Online (Sandbox Code Playgroud)
OUtput:
Proj_Com_Sum comp_1 comp_2 comp_3 Proj_Val_sum val_1 val_2 val_3 \
0 70 10 20 35 67 20 30 15
1 100 50 30 25 70 25 30 15
Com_total Val_total Proj_Tot_diff
0 65 65 -5
1 105 70 5
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
47 次 |
| 最近记录: |