# 如何获取 Pandas DataFrame 的列的平均值

Ahmed Waheed 2023年1月30日

``````import pandas as pd

data = {
"name": ["Oliver", "Harry", "George", "Noah"],
"percentage": [90, 99, 50, 65],
}
df = pd.DataFrame(data)
``````

``````     name  percentage  grade
0  Oliver          90     88
1   Harry          99     76
2  George          50     95
3    Noah          65     79
``````

## `df.mean()` 方法来计算 Pandas DataFrame 列的平均值

``````import pandas as pd

data = {
"name": ["Oliver", "Harry", "George", "Noah"],
"percentage": [90, 99, 50, 65],
}
df = pd.DataFrame(data)
print(mean_df)
``````

``````84.5
``````

``````import pandas as pd

data = {
"name": ["Oliver", "Harry", "George", "Noah"],
"percentage": [90, 99, 50, 65],
}
df = pd.DataFrame(data)
mean_df = df.mean()
print(mean_df)
``````

``````percentage    76.0
dtype: float64
``````

## `df.describe()` 方法

``````import pandas as pd

data = {
"name": ["Oliver", "Harry", "George", "Noah"],
"percentage": [90, 99, 50, 65],
}
df = pd.DataFrame(data)
print(df.describe())
``````

``````       percentage      grade
count    4.000000   4.000000
mean    76.000000  84.500000
std     22.524061   8.660254
min     50.000000  76.000000
25%     61.250000  78.250000
50%     77.500000  83.500000
75%     92.250000  89.750000
max     99.000000  95.000000
``````

`df.describle()` 方法的结果是一个 DataFrame，因此，你可以通过引用列名和行名来获得 `percentage``grade` 的平均值。

``````df.describe()["grade"]["mean"]
df.describe()["percentage"]["mean"]
``````

`df.describe()` 也可以用于特定的列。让我们将此函数应用于等级列。

``````import pandas as pd

data = {
"name": ["Oliver", "Harry", "George", "Noah"],
"percentage": [90, 99, 50, 65],
}
df = pd.DataFrame(data)
``````

``````count     4.000000
mean     84.500000
std       8.660254
min      76.000000
25%      78.250000
50%      83.500000
75%      89.750000
max      95.000000
``````df["grade"].describe()["mean"]