I would first modify how you import the data to:

df = DataFrame(olympic_medal_counts).set_index('country_name')

I would then calculate a new column containing the sum of the rows for the toal number of medals per country.

df['medal total'] = df.sum(axis=1)

Results:

                   bronze  gold  silver  medal total
country_name                                     
Russian Fed.         9    13      11           33
Norway              10    11       5           26
Canada               5    10      10           25
United States       12     9       7           28
Netherlands          9     8       7           24
Germany              5     8       6           19
Switzerland          2     6       3           11
Belarus              1     5       0            6
Austria              5     4       8           17
France               7     4       4           15
Poland               1     4       1            6
China                2     3       4            9
Korea                2     3       3            8
Sweden               6     2       7           15
Czech Republic       2     2       4            8
Slovenia             4     2       2            8
Japan                3     1       4            8
Finland              1     1       3            5
Great Britain        2     1       1            4
Ukraine              1     1       0            2
Slovakia             0     1       0            1
Italy                6     0       2            8
Latvia               2     0       2            4
Australia            1     0       2            3
Croatia              0     0       1            1
Kazakhstan           1     0       0            1

Finally, subset the the DataFrame for rows with medal totals greater than or equal to 1 and find the average of the columns.

df[df['medal total'] >= 1].apply(np.mean)

Results:

bronze          3.807692
gold            3.807692
silver          3.730769
medal total    11.346154

This could also be accomplished in one line using:

df[ df.sum(axis=1) >= 1 ].apply(np.mean)
Answer from Andrew on Stack Overflow
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.mean.html
pandas.DataFrame.mean — pandas documentation
This computes the arithmetic mean of the values in each column (or row when axis=1), skipping missing values by default. ... Axis for the function to be applied on.
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.apply.html
pandas.DataFrame.apply — pandas 3.0.1 documentation
However if the apply function returns a Series these are expanded to columns. ... Positional arguments to pass to func in addition to the array/series. ... Only has an effect when func is a listlike or dictlike of funcs and the func isn’t a string. If “compat”, will if possible first translate the func into pandas methods (e.g.
🌐
Pandas
pandas.pydata.org › docs › dev › reference › api › pandas.DataFrame.mean.html
pandas.DataFrame.mean — pandas 3.0.0rc2+20.g501c5052ca documentation
>>> df = pd.DataFrame({"a": [1, 2], "b": [2, 3]}, index=["tiger", "zebra"]) >>> df a b tiger 1 2 zebra 2 3 >>> df.mean() a 1.5 b 2.5 dtype: float64
🌐
GeeksforGeeks
geeksforgeeks.org › python-pandas-dataframe-mean
Pandas DataFrame mean() Method - GeeksforGeeks
May 17, 2024 - Pandas dataframe.mean() function returns the mean of the values for the requested axis. If the method is applied on a pandas series object, then the method returns a scalar value which is the mean value of all the observations in the Pandas ...
Top answer
1 of 5
4

I would first modify how you import the data to:

df = DataFrame(olympic_medal_counts).set_index('country_name')

I would then calculate a new column containing the sum of the rows for the toal number of medals per country.

df['medal total'] = df.sum(axis=1)

Results:

                   bronze  gold  silver  medal total
country_name                                     
Russian Fed.         9    13      11           33
Norway              10    11       5           26
Canada               5    10      10           25
United States       12     9       7           28
Netherlands          9     8       7           24
Germany              5     8       6           19
Switzerland          2     6       3           11
Belarus              1     5       0            6
Austria              5     4       8           17
France               7     4       4           15
Poland               1     4       1            6
China                2     3       4            9
Korea                2     3       3            8
Sweden               6     2       7           15
Czech Republic       2     2       4            8
Slovenia             4     2       2            8
Japan                3     1       4            8
Finland              1     1       3            5
Great Britain        2     1       1            4
Ukraine              1     1       0            2
Slovakia             0     1       0            1
Italy                6     0       2            8
Latvia               2     0       2            4
Australia            1     0       2            3
Croatia              0     0       1            1
Kazakhstan           1     0       0            1

Finally, subset the the DataFrame for rows with medal totals greater than or equal to 1 and find the average of the columns.

df[df['medal total'] >= 1].apply(np.mean)

Results:

bronze          3.807692
gold            3.807692
silver          3.730769
medal total    11.346154

This could also be accomplished in one line using:

df[ df.sum(axis=1) >= 1 ].apply(np.mean)
2 of 5
3

I have just used the concept of R language in pandas to solve it and it works. Try this code under # your code here

sub_df = df[(df.gold >= 1) | (df.silver >= 1) | (df.bronze >= 1)] ### subsetting the data frame
avg_count = sub_df.mean(axis=0) ### axis 0 for column wise mean

return avg_count

In python 3 IDE (like pycharm) you should use

return print(avg_count) 

then put the main function outside of the indentation to find the answer

avg_medal_count()
🌐
Spark By {Examples}
sparkbyexamples.com › home › pandas › how to get column average or mean in pandas dataframe
How to Get Column Average or Mean in Pandas DataFrame - Spark By {Examples}
December 12, 2024 - To get column average or mean from pandas DataFrame use either mean() or describe() method. The mean() method is used to return the mean of the values along the specified axis. If you apply this method on a series object, it returns a scalar ...
🌐
Javatpoint
javatpoint.com › pandas-dataframe-mean
Pandas DataFrame.mean() - javatpoint
Pandas The main task of function is to apply some aggregation to one or more column. Most frequently used aggregations are: sum: It is used to return the sum of the values for the requested axis.
🌐
Vultr Docs
docs.vultr.com › python › third-party › pandas › DataFrame › mean
Python Pandas DataFrame mean() - Calculate Column Mean | Vultr Docs
December 24, 2024 - import pandas as pd data = { 'A': ... of lists. Applying mean() computes the average across each numeric column, resulting in a Series where each index corresponds to a column name from the DataFrame....
Find elsewhere
🌐
Dataquest
dataquest.io › blog › tutorial-how-to-use-the-apply-method-in-pandas
Learn How to Use the Apply Method in Pandas With This Tutorial
March 6, 2023 - In this tutorial, we learned what the apply() method does and how to use it by going through different examples. The apply() method is a powerful and efficient way to apply a function on every value of a Series or DataFrame in pandas.
🌐
W3Schools
w3schools.com › python › pandas › ref_df_mean.asp
Pandas DataFrame mean() Method
import pandas as pd data = [[1, 1, 2], [6, 4, 2], [4, 2, 1], [4, 2, 3]] df = pd.DataFrame(data) print(df.mean()) Try it Yourself »
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.core.groupby.GroupBy.mean.html
pandas.core.groupby.GroupBy.mean — pandas 1.5.3 documentation
Apply a function groupby to each row or column of a DataFrame. ... >>> df = pd.DataFrame({'A': [1, 1, 2, 1, 2], ... 'B': [np.nan, 2, 3, 4, 5], ... 'C': [1, 2, 1, 1, 2]}, columns=['A', 'B', 'C']) Groupby one column and return the mean of the remaining columns in each group.
🌐
EDUCBA
educba.com › home › software development › software development tutorials › pandas tutorial › pandas dataframe.mean()
Pandas DataFrame.mean()
April 3, 2023 - The most common method to represent ... programming the value of the mean can be determined by using the Pandas DataFrame.mean() function....
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
Pandas
pandas.pydata.org › pandas-docs › version › 1.2 › reference › api › pandas.core.groupby.GroupBy.mean.html
pandas.core.groupby.GroupBy.mean — pandas 1.2.5 documentation
Apply a function groupby to each row or column of a DataFrame. ... >>> df = pd.DataFrame({'A': [1, 1, 2, 1, 2], ... 'B': [np.nan, 2, 3, 4, 5], ... 'C': [1, 2, 1, 1, 2]}, columns=['A', 'B', 'C']) Groupby one column and return the mean of the remaining columns in each group.
🌐
W3Schools
w3schools.com › python › pandas › ref_df_apply.asp
Pandas DataFrame apply() Method
import pandas as pd def calc_sum(x): return x.sum() data = { "x": [50, 40, 30], "y": [300, 1112, 42] } df = pd.DataFrame(data) x = df.apply(calc_sum) print(x) Try it Yourself »
🌐
Stack Overflow
stackoverflow.com › questions › 57800754 › how-to-get-mean-value-by-function-in-pandas
python - How to get mean value by function in pandas - Stack Overflow
Your errors comes from your attempt of trying to take the mean of a single individual float value, which is not possible. You can see that you are trying to take the mean of a single value by executing the following: >> data['column'].apply(print) 1.0 # your function tries to apply mean to this value 4.0
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.Series.mean.html
pandas.Series.mean — pandas 3.0.1 documentation
Return the mean of the values over the requested axis. ... Axis for the function to be applied on.
🌐
Spark By {Examples}
sparkbyexamples.com › home › pandas › pandas.dataframe.mean() examples
pandas.DataFrame.mean() Examples - Spark By {Examples}
December 6, 2024 - Let’s create a DataFrame from Dict and learn how to use the mean with an example. import pandas as pd import numpy as np technologies = ({ 'Courses':["Spark",np.nan,"pandas","Java","Spark"], 'Fee' :[20000,25000,30000,22000,np.NaN], 'Duration':['30days','40days','35days','60days','50days'], 'Discount':[1000,2500,1500,1200,3000] }) df = pd.DataFrame(technologies) print(df) # Output: # Courses Fee Duration Discount # 0 Spark 20000.0 30days 1000 # 1 NaN 25000.0 40days 2500 # 2 pandas 30000.0 35days 1500 # 3 Java 22000.0 60days 1200 # 4 Spark NaN 50days 3000
🌐
DataCamp
datacamp.com › tutorial › pandas-apply
Pandas .apply(): What It Does, When It Helps, and Faster Alternatives | DataCamp
October 6, 2025 - Series.apply(func) calls func on each element (or the whole Series, depending on signatures in recent versions). Row-wise vs. column-wise: axis=1 means “per row.” axis=0 (the default) means “per column.” · Return shape rules (pandas ≥0.23): If your function returns a scalar per ...