Pandas Dataframe:使用.groupby和.idxmax()检索Pandas Dataframe中的最大值



我有一个Pandas Dataframe,其中包含一系列由邻里组邻里room_type分组的Airbnb价格。我的目标是返回每个room_type每个街区的最大平均价格,并且只返回这个。

我的方法是使用.groupby和.idxmax()来获取索引w.r.t的最大值,然后相应地迭代并将索引位置附加到列表中,该列表用于过滤目的。(这个链接很有用:Python Pandas Dataframe select row by max value in group)

df = airbnb.loc[airbnb['neighbourhood'].isin(list(combined['neighbourhood']))].groupby(['neighbourhood','room_type']).mean().sort_values(by=['Revenues'],ascending=False)['Revenues'].reset_index().sort_values(by=['neighbourhood','room_type']).reset_index()
tmp_list = []
test = pd.DataFrame(df.groupby(['neighbourhood','room_type'])['Revenues'].idxmax(axis=0)).reset_index()
#Re-Assign Revenues back to the Dataframe for Reference
test['Actual_Revenues'] = df['Revenues']
#The Maximum Revenue Value for each Sub Grouping is Returned by Index
for i in neighbourhood_list:
print(test[test['neighbourhood']==i])
max_index_list = test[test['neighbourhood']==i].sort_values(by='Actual_Revenues', ascending=False).head(1)['Revenues']
print(max_index_list)
tmp_list.append(list(max_index_list))

tmp_list = list(np.concatenate(tmp_list).flat)
df[df.index.isin(tmp_list)]

现在运行得很顺利,但我不认为这是非常高效的(特别是我的循环)。

我如何进一步优化我的代码以减少冗余并使我的代码更python化?

我们的预期输出如下所示,仅显示每个小区的最大房间类型和价格。(即每个邻居有一个唯一的条目)。

非常感谢。

这是一个可复制的数据集,你可以用来测试代码:https://docs.google.com/spreadsheets/d/1x-ktbfJouPzI0hokKw0fSNXAwmD8Q8Yd/edit?usp=sharing& ouid = 101578147330059746959, rtpof = true& sd = true

这是我的输出的图片(使用完整的数据集,而不是部分显示的数据集),这只是为了显示每个邻居显示的最大价格的概念。如果一个邻居有多种房间类型(他们会有),它将返回最高价格和相关的房间类型。

https://ibb.co/HnBysVc

使用Series.nlargest():

# Get mean price per room_type per neighbourhood
means = df.groupby(['neighbourhood', 'room_type'])['price'].mean()
# Get the maximum mean price per room_type per neighbourhood
max_means = (means.groupby(level=0, group_keys=False)
.nlargest(1)
.reset_index())

max_means的前五行:

1201401508999

最新更新