If you only want the mean of the weight column, select the column (which is a Series) and call .mean():
In [479]: df
Out[479]:
ID birthyear weight
0 619040 1962 0.123123
1 600161 1963 0.981742
2 25602033 1963 1.312312
3 624870 1987 0.942120
In [480]: df.loc[:, 'weight'].mean()
Out[480]: 0.83982437500000007
Answer from DSM on Stack OverflowIf you only want the mean of the weight column, select the column (which is a Series) and call .mean():
In [479]: df
Out[479]:
ID birthyear weight
0 619040 1962 0.123123
1 600161 1963 0.981742
2 25602033 1963 1.312312
3 624870 1987 0.942120
In [480]: df.loc[:, 'weight'].mean()
Out[480]: 0.83982437500000007
Try df.mean(axis=0) , axis=0 argument calculates the column wise mean of the dataframe so the result will be axis=1 is row wise mean so you are getting multiple values.
[pandas] df.mean() gives different results to calculating mean in Excel?
In a pandas dataframe, how to find the average value within specific categories as denoted in another column. See example in the description.
Mean of a list of Series [Pandas]
Is Numpy always more efficient than Pandas? And how much should we rely on Python anyway?
EDIT: RESOLVED. I was being a complete moron. See comment if you want a laugh.
Here's the situation: I've webscraped some sports stats and saved them in a DF. I then add a new row which calculates the mean of each column (mean number of hits, runs, etc). I then save the data to CSV.
When looking at the data in Excel, I noticed that the means looked off. I calculated them in Excel (using both =sum(firstCell:lastCell)/#rows and =AVERAGE(firstCell:lastCell). Both of those methods agreed with each other, but were wildly different (and at a glance, closer to what I'd expect) than the df.mean() values
Here's the Python code (I've shortened the paths for brevity but they're operational in the real code):
import pandas as pd
from pathlib import Path
DATA_DIR = "[...]/data"
p = Path(DATA_DIR)
def read_data():
lst = pd.read_html(f"[...]/batting")
df = lst[0]
df = df.fillna(0)
return df
batting_df = read_data()
batting_df.loc['lgAvg'] = batting_df.mean()
# Then export to CSV.I've just noticed, having looked at them more closely, that the lgAvg values are pretty much (but not always exactly) double the =AVERAGE() values from Excel. They're double to within 1 DP.
Any idea what's causing this?
I have this:
| Category | Value |
|---|---|
| A | 2 |
| A | 4 |
| A | 6 |
| A | 4 |
| B | 3 |
| B | 4 |
| B | 5 |
And I want this:
| Category | Value |
|---|---|
| A | 4 |
| B | 4 |
I want the average values, but specifically within the A and B categories.
Thanks!