Python Forum
Dataframe mean calculation problem: do we have to loop?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dataframe mean calculation problem: do we have to loop?
#1
Suppose we have a very simple dataframe.

import pandas as pd
df = pd.DataFrame({'A': [1, 2, 5, 6, 7], 'B': [20, 30, 50, 90, 80]})
print(df)
A B
0 1 20
1 2 30
2 5 50
3 6 90
4 7 80

The question is simple: How do we create a third row 'C' such that the following is true?

df.C[0] = mean of all the 10 numbers
df.C[1] = mean of 2, 5, 6, 7, 30, 50, 90, 80
df.C[2] = mean of 5, 6, 7, 50, 90, 80
df.C[3] = mean of 6, 7, 90, 80
df.C[4] = mean of 7, 80

I've read dozens of relevant tutorials online but all of them only teach how to get a single mean for a single row.
Any help would be much appreciated.
Reply
#2
I got it, though I expected something much simpler.

df['C'] = 0.0
for i in df.index:
    df['C'][i] = df[['A', 'B']][i:].mean().mean()
print(df)
But do we have to use this for loop to go through all values? One of the best things of dataframe is that it can deal with a complex frame once only when applying function, without the need of going through looping which is not good for optimal performance.

I hope there's a more elegant solution!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  While Loop Problem Benno2805 1 537 Sep-06-2023, 04:51 PM
Last Post: deanhystad
  Stock Return calculation problem LFin 10 1,949 Sep-26-2022, 04:28 PM
Last Post: deanhystad
  2-dataframe, datetime lookup problem Mark17 0 1,215 Jan-27-2022, 01:02 AM
Last Post: Mark17
  Increase the speed of a python loop over a pandas dataframe mcva 0 1,290 Jan-21-2022, 06:24 PM
Last Post: mcva
Question How can I merge several images via loop using the information of a dataframe? noahverner1995 1 1,397 Dec-31-2021, 05:03 AM
Last Post: noahverner1995
  Loop reading csv file problem faustineaiden 1 1,539 Dec-11-2021, 08:40 AM
Last Post: ibreeden
  for loop in dataframe in pandas Paulman 7 2,673 Dec-02-2021, 12:15 AM
Last Post: bowlofred
  problem writing dataframe to oracle aliyesami 4 2,586 Sep-25-2021, 11:20 PM
Last Post: SamHobbs
  Problem in saving .xlsm (excel) file using pandas dataframe in python shantanu97 2 4,161 Aug-29-2021, 12:39 PM
Last Post: snippsat
  Dataframe problem stylingpat 3 2,763 Mar-22-2021, 10:36 AM
Last Post: stylingpat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020