如何在 Pandas DataFrame 中的组中应用函数?
在本文中,让我们看看如何在 Pandas Dataframe 中的组中应用函数。执行此任务要遵循的步骤是——
- 导入必要的库。
- 将数据设置为Pandas DataFrame 。
- 使用apply函数查找不同的统计度量,如滚动平均值、平均值、总和、最大值和最小值。您可以为此使用lambda函数。
下面是实现——
让我们创建数据框。
Python3
#import libraries
import pandas as pd
# set up the data
data_dict = {"Student House": ["Lavender", "Lavender", "Lavender",
"Lavender", "Daisy", "Daisy",
"Daisy", "Daisy", "Daffodils",
"Daffodils", "Daffodils", "Daffodils"],
"Points": [10, 4, 6, 7, 3, 8, 9, 10, 4, 5, 6, 7]}
data_df = pd.DataFrame(data_dict)
print("Dataframe : ")
data_df
Python3
# finding rolling mean
rolling_mean = data_df.groupby("Student House")["Points"].apply(
lambda x: x.rolling(center=False, window=2).mean())
print("Rolling Mean:")
print(rolling_mean)
Python3
# finding mean
mean = data_df.groupby("Student House")["Points"].apply(
lambda x: x.mean())
print("Mean:")
print(mean)
Python3
# finding sum
sum = data_df.groupby("Student House")["Points"].apply(
lambda x: x.sum())
print("Sum:")
print(sum)
输出:
示例 1:
蟒蛇3
# finding rolling mean
rolling_mean = data_df.groupby("Student House")["Points"].apply(
lambda x: x.rolling(center=False, window=2).mean())
print("Rolling Mean:")
print(rolling_mean)
输出:
示例 2:
蟒蛇3
# finding mean
mean = data_df.groupby("Student House")["Points"].apply(
lambda x: x.mean())
print("Mean:")
print(mean)
输出:
示例 3:
蟒蛇3
# finding sum
sum = data_df.groupby("Student House")["Points"].apply(
lambda x: x.sum())
print("Sum:")
print(sum)
输出: