如何获得熊猫出现值的最小次数

时间:2020-07-23 07:17:39

标签: python pandas dataframe pandas-groupby

          home_team_name  home_team_goal_count
0         Bayern München                     2
1         Bayern München                     2
2         Bayern München                     1
3                   Köln                     2
4                   Köln                     2

我将变量home_team_name上的数据分组。

df.groupby("home_team_name")

home_team_goal_count的值只能是2或1。我想获得最小的出现次数 每个组中的值。我想要的结果是拜仁慕尼黑1,科隆0。为了说明拜仁慕尼黑的2乘2和1乘1,因此最小值为1。科恩的2乘2和0乘以1,因此最小值为0。

4 个答案:

答案 0 :(得分:3)

首先对值SeriesGroupBy.value_counts进行计数,对所有组合0进行整形并添加1,2,最后对min进行最小值计算:

s = (df.groupby("home_team_name")['home_team_goal_count']
       .value_counts()
       .unstack(fill_value=0)
       .min(axis=1))

print (s)
home_team_name
Bayern München    1
Köln              0
dtype: int64

详细信息

print (df.groupby("home_team_name")['home_team_goal_count']
         .value_counts()
         .unstack(fill_value=0))
home_team_goal_count  1  2
home_team_name            
Bayern München        1  2
Köln                  0  2

在可能的情况下,1或输入数据中仅2的值是必要的reindex

s = (df.groupby("home_team_name")['home_team_goal_count']
       .value_counts()
       .unstack(fill_value=0)
       .reindex([1, 2], axis=1, fill_value=0) 
       .min(axis=1))

答案 1 :(得分:3)

让我们尝试使用pd.crosstab

pd.crosstab(df['home_team_name'], df['home_team_goal_count'])\
    .reindex([1, 2], axis=1, fill_value=0).min(1)

结果:

home_team_name
Bayern München    1
Köln              0
dtype: int64

答案 2 :(得分:1)

import pandas as pd
import numpy as np
list1=['Bayern Munchen','Bayern Munchen','Bayern Munchen','FC Koln','FC Koln']
list2=[2,2,1,2,2]
d={'Home Team Name':list1,'Home Team Goal Count':list2}
data=pd.DataFrame(d)

data['Name']= data['Home Team Name'] +" "+ data['Home Team Goal Count'].astype(str)

data['Name']
Out[39]: 
0    Bayern Munchen 2
1    Bayern Munchen 2
2    Bayern Munchen 1
3           FC Koln 2
4           FC Koln 2

name,count=np.unique(data['Name'].tolist(),return_counts=True)

name=[' '.join(x.split(' ')[:-1]) for x in name]

name
Out[99]: ['Bayern Munchen', 'Bayern Munchen', 'FC Koln']

min_val=pd.DataFrame({"Name":name,"Count":count})

name=[]
min_val_count=[]
for x in min_val.Name.unique():
    name.append(min_val[min_val.Name!=x].min()[0])
if min_val[min_val.Name!=x].min()[1]==2:
    min_val_count.append(0)
else:
    min_val_count.append(min_val[min_val.Name!=x].min()[1])


minimum_val_dict=dict(zip(name,min_val_count))

minimum_val_dict
Out[104]: {'FC Koln': 0, 'Bayern Munchen': 1}

与以上答案相比版本稍长。

答案 3 :(得分:0)

执行此操作的另一种方法是使用类别变量,因为存在有限的状态集。所以:

(
    df
    .astype({"home_team_goal_count": "category"})
    .groupby("home_team_name")["home_team_goal_count"]
    .apply(lambda x: x.value_counts().min())
)

如果您想知道哪个值最少出现一次,可以调用.idxmin()而不是.min()