Consider that I already figure it out a way to solve my problem, but i would like to find a better way and/or understanding a bit more about pandas dataframe and apply/lambda functions. I have a pandas DataFrame like this:
A
0 [43,45,51,...,32]
1 [43,45,51,...,32]
2 [43,45,51,...,32]
... ...
... ...
... ...
n [43,45,51,...,32]
The column A contains per each row 64 elements. What I would like is to apply a function to each row that:
- sum only certain elements of the column A (let's say indexes 18,27,34,45)
- make the average of that sum
- put the average in a new column called B
so that, at the end I should have something like this:
A B (mean over few elements)
0 [43,45,51,...,32] 50
1 [42,55,41,...,68] 60
2 [11,30,29,...,23] 30
... ... ...
... ... ...
... ... ...
n [33,45,84,...,77] 70
Right now I was able to do that using a numpy array in which i stored column A like this:
a = np.array(df["A"])
k =[18,27,34,45]
for i in range(n):
vector = 0
for idx, val in enumerate(k):
vector = vector + a[i][val]
mean.append(vector/16)
But i was thinking about a more elegant way with the apply/lamdba method. It will be also ok if, instead of creating another column I will append values to a numpy list. Thank you in advance and cheers.