# 如何獲取 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)

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())

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.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