xhan
xhan

Reputation: 6287

Add column by previous columns values in Pandas

Here is table:

6   30  98  298 588 1598
36  2.0 NaN NaN NaN NaN NaN
50  1.0 NaN NaN NaN NaN NaN

Here is my dirty way to add new 'total' column:

df_cz['total'] = df_cz[6] *6 + df_cz[30] *30 + df_cz[98] *98 + ...

Is there a better way to calculate 'total' values base on table head value and each row values.

Upvotes: 1

Views: 69

Answers (1)

jezrael
jezrael

Reputation: 862761

You can use mul with columns names converted to_series with sum:

print (df_cz)
    6   30  98  298  588  1598
0  36  2.0 NaN  NaN  NaN   NaN
1  50  1.0 NaN  NaN  NaN   NaN

df_cz['total'] = df_cz.mul(df_cz.columns.to_series()).sum(axis=1)
print (df_cz)
    6   30  98  298  588  1598  total
0  36  2.0 NaN  NaN  NaN   NaN  276.0
1  50  1.0 NaN  NaN  NaN   NaN  330.0

Upvotes: 1

Related Questions