I want to average the third column onwards

Viewed 50

I hope you are well. I am new. I am trying to add certain columns but not to all, and I require your help.

W=[[77432664,6,2,4,3,4,3],
    [6233234,7,3,2,5,3,1],
    [3412455221,8,3,2,4,5,5]]

rows=len(W)
columns=len(W[0])

for i in range(rows):
    T=sum(W[i])
    W[i].append(T)
4 Answers

I assume by "add" you mean "sum" and not "insert". If so, then you can use what is called a slice:

for row in rows:
   t = sum(row[1:])
   row.append(t)

row[1:] takes all but the first element of the list row. For more information on this syntax, you should google "python slice".

Also notice how I am iterating over rows directly, rather than using an index. This is the most common way to do a loop in Python.

You can create a subarray in python by specifying the column range and then add it. Below code demonstrate the addition of column 2,3,4,5,6 in Python.

W=[[77432664,6,2,4,3,4,3],
[6233234,7,3,2,5,3,1],
[3412455221,8,3,2,4,5,5]]

rows=len(W)
columns=len(W[0])

for i in range(rows):
    T=sum(W[i][2:6]) #For i=0 it retreives subarray [2,4,3,4,3] then add it to get T=16
    W[i].append(T)

I'd suggest using pandas sum method using over axis=0:

# numeric of columns
my_cols_n = [2,3,4,5,6]

# Get cols by name
my_cols = [x for x,i in enumerate(list(df.columns)) if i in my_cols_n]

# Get Sum
df["my_sum"] = df[my_cols].sum(axis=0)

To add to @Code-Apprentice answer - consider using numpy for similar assignments:

import numpy as np

W=[[77432664,6,2,4,3,4,3],
    [6233234,7,3,2,5,3,1],
    [3412455221,8,3,2,4,5,5]]

W=np.array(W)

>>> print(W[:, 3:].mean(axis=1))

[3.5  2.75 4.  ]

Especially with the growth of complexity of matrix operations - you will quickly see big advantages of numpy

Related