Python Pandas-查找2个从属属性的最大计数,并用该值替换重复的行
我在熊猫公司工作,我有一个数据集/数据框,看起来像这样Python Pandas-查找2个从属属性的最大计数,并用该值替换重复的行,python,pandas,dataframe,pandas-groupby,Python,Pandas,Dataframe,Pandas Groupby,我在熊猫公司工作,我有一个数据集/数据框,看起来像这样 venueId venueCategoryId venueCategory v1 vc1 Airport v1 vc2 Park v1
venueId venueCategoryId venueCategory
v1 vc1 Airport
v1 vc2 Park
v1 vc1 Airport
v2 vc3 American Restaurant
v3 vc4 Italian Restaurant
v3 vc5 Restaurant
venueId代表独特的场馆,类别代表场馆的类型。CategoryId和CategoryName值是相关的
我试图用该场馆中最高的类别来替换场馆的venueCategoryId和VenueCegory
我想要得到的结果是:
venueId venueCategoryId venueCategory
v1 vc1 Airport
v2 vc3 American Restaurant
v3 vc4 Italian Restaurant
我试图使用“venueId”列上的groupby来分组并查找计数,然后替换为最高计数。但我不知道如何将venueCategoryId和venueCategory作为pandas中的一个依赖列,并找到最多2列并替换它们 这里有一个解决方案。很可能有一种更为宽宏大量的方法
# combine id and category series
df['venueIdCat'] = list(zip(df.venueCategoryId, df.venueCategory))
# groupby venueId and extract mode
res = df.groupby('venueId')['venueIdCat'].apply(pd.Series.mode).reset_index()
# unsplit id and category
res = res.join(pd.DataFrame(res['venueIdCat'].values.tolist(),
columns=['venueCategoryId', 'venueCategory']))
# select required columns
res = res[['venueId', 'venueCategoryId', 'venueCategory']]
print(res)
venueId venueCategoryId venueCategory
0 v1 vc1 Airport
1 v2 vc3 AmericanRestaurant
2 v3 vc4 ItalianRestaurant
使用集合的替代解决方案。计数器:
from collections import Counter
# combine id and category series
df['venueIdCat'] = list(zip(df.venueCategoryId, df.venueCategory))
# groupby venueId and extract mode
res = df.groupby('venueId')['venueIdCat'].apply(lambda x: Counter(x).most_common()[0][0]).reset_index()
# unsplit id and category
res = res.join(pd.DataFrame(res['venueIdCat'].values.tolist(),
columns=['venueCategoryId', 'venueCategory']))
# select required columns
res = res[['venueId', 'venueCategoryId', 'venueCategory']]
print(res)
venueId venueCategoryId venueCategory
0 v1 vc1 Airport
1 v2 vc3 AmericanRestaurant
2 v3 vc4 ItalianRestaurant
它完成了大部分工作。唯一的问题是,当VenueCoteGoryId的数字相同时(例如:v1而不是vc1,它只有一次)。然后它同时保留了vc1和vc2,我想保留任何一个都不重要。@KevinStephenBiswas,对不起,我不明白。也许你可以举一个例子来说明期望的输出与我概述的方法有什么不同?@KevinStephenBiswas,请使用新的输入和期望的输出-我无法阅读注释中的代码。在v3中,两个类别都不会出现一次。当使用该模式时,它保留v3的两行,但我想要其中一行。