-1

I have a dataframe with some columns named incrementally (e.g. A_1, A_2, A_3, ... ). I want to perform an operation on them, the-like of:

A_1*1 + A_2*2 + A_3*3 + ...

Is there a quick way to do that, instead of just writing down the name of all the columns (they are 15 in total)?

danie
  • 155
  • 1
  • 10

3 Answers3

0

iterate through the columns, extract the factor to multiply by and reasssign multiplied values back to those columns

for k in df.columns:
    factor = k.split('_')[-1]
    df[k] = df[k]*int(factor)
Haleemur Ali
  • 26,718
  • 5
  • 61
  • 85
0

For example you have following dataframe

df=pd.DataFrame({'A_1':[1,2],'A_2':[1,2]})

We just need to using str.split and mul

s=df.columns.str.split('_').str[1].values.astype('int')

df.mul(s,axis=1)

Out[508]: 
   A_1  A_2
0    1    2
1    2    4

If need sum

df.mul(s,axis=1).sum(axis=1)
Out[509]: 
0    3
1    6
dtype: int64
BENY
  • 317,841
  • 20
  • 164
  • 234
0

you can also use apply such as:

df['total'] = df.apply(lambda x: sum([x[col]*int(col.split('_')[-1]) for col in df.columns]),axis=1)

Note: because I add a column in df, I can't perform the same operation twice.

Ben.T
  • 29,160
  • 6
  • 32
  • 54