在数据框中分组后计算值大于特定行的行数

Counting the number of rows having values greater than particular row after grouping in a dataframe

我有一个包含重要城市人口的数据框。 Dataframe image

它包含来自不同国家的城市。在特定国家/地区的所有城市中,只有一个城市被认为是主要城市(在 'capital' 列中提到)。我需要找出人口大于主要城市的城市数量 city.Kindly 提供一种解决方案?

使用:

#test primary
m = df['capital'].eq('primary')

#get dict for primary population
d = df[m].set_index('country')['population'].to_dict()

#filter not primary
df1 = df[~m].copy()

#compare non primary population with primary by map and count with sum
out = df1['population'].gt(df1['country'].map(d)).sum()

#filter compare rows if necessary
df2 = df1[df1['population'].gt(df1['country'].map(d))]