要按酒店对数据进行分组并计算每家酒店收入的最小值、中值和最大值,您可以使用 Pandas DataFrame 的 groupby 和 agg 方法。这是一个例子:
import pandas as pd
# Create a DataFrame
df = pd.DataFrame(
{
"Hotel": ["Abu", "Zain", "Show", "Zint", "Abu", "Zain", "Abu",
"Abu", "Abu", "Abu", "Show", "Zint"],
"Earning": [1000, 400, 500, 300, 500, 700, 500, 500, 800, 1600, 1300, 600],
}
)
# Group the data by hotel and calculate the min, median, and max of the earning
df_grouped = df.groupby("Hotel").agg(["min", "median", "max"])
# Print the aggregates values for the hotel "Abu"
print(df_grouped.loc["Abu"])
在上面的代码中,首先,我们使用给定的数据创建一个 Pandas DataFrame。然后,我们按酒店对数据进行分组,并使用 groupby 和 agg 方法计算每家酒店收入的最小值、中值和最大值。最后,我们使用 DataFrame 的 loc 方法打印酒店“Abu”的聚合值。输出将是:
Earning
min median max
Abu 500 650 1600
然后,您可以使用 DataFrame 的 iloc 方法访问最小值、中值和最大值。这是一个例子:
# Access the values of the min, median, and max for the hotel "Abu"
print(df_grouped.loc["Abu"].iloc[0])
输出将是:
min 500
median 650
max 1600
Name: Earning, dtype: int64
然后,您可以使用 tolist 方法将值转换为列表:
# Convert the values of the min, median, and max to a list
print(df_grouped.loc["Abu"].iloc[0].tolist())
输出将是:
[500.0, 650.0, 1600.0]