Pandas:计算列中相同但来自不同索引的值

Pandas: count identical values in columns but from different index

我有一个代表餐厅顾客评分的数据框。 rating_year 是评分的年份,first_year 是餐厅开业的年份,last_year 是餐厅的最后营业年份。

我在这里所做的问题是我将 restaurant_id 和 first_year 分组并进行计数,但我不排除具有相同 ID 的其余部分。 我不知道这样做的语法。 有人可以帮忙吗?

data = {'rating_id': ['1', '2','3','4','5','6','7','8','9'],
        'user_id': ['56', '13','56','99','99','13','12','88','45'],
        'restaurant_id':  ['xxx', 'xxx','yyy','yyy','xxx','zzz','zzz','eee','eee'],
        'star_rating': ['2.3', '3.7','1.2','5.0','1.0','3.2','1.0','2.2','0.2'],
        'rating_year': ['2012','2012','2020','2001','2020','2015','2000','2003','2004'],
        'first_year': ['2012', '2012','2001','2001','2012','2000','2000','2001','2001'],
        'last_year': ['2020', '2020','2020','2020','2020','2015','2015','2020','2020'],
        }


df = pd.DataFrame (data, columns = ['rating_id','user_id','restaurant_id','star_rating','rating_year','first_year','last_year'])
df['star_rating'] = df['star_rating'].astype(float)

df['nb_rating'] = (
    df.groupby('restaurant_id')['rating_id'].transform('count')
)



#here
df['nb_opened_sameYear'] = (
    df.groupby('restaurant_id')['first_year']
    .transform('count')
)

df.head(10)

IIUC,您想 groupby first_year 和 transformnunique 在 restaurant_id 列上。尝试:

df['nb_opened_sameYear'] = (
    df.groupby('first_year')['restaurant_id']
    .transform('nunique')
)