Python和Pandas:在一列中以d表示人数

2024-05-16 09:04:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我基本上有一个3列的数据集。你知道吗

Restaurant | Customer | Date

这里有多家餐厅、顾客和约会场所。 使用python/pandas,我试图找出每一位顾客的数量,他们至少去过一家餐厅3次或3次以上,并且分别去过任何一家餐厅3次或3次以上。(例如:1人参观了3家不同的餐厅)

我还想看看独特的设备,谁参观了餐厅3次以上的计数。你知道吗

到目前为止,我已经:

df.groupby(['Restaurant','name'])['date'].value_counts()

这给了我按日期访问的次数,但我要的是实际访问的日期数。(唯一日期)

谢谢你的帮助!我希望我说得够清楚。你知道吗


Tags: 数据namepandasdf数量datecustomer餐厅
2条回答

设置符合您的解释的数据场景。你知道吗

>>> df = pd.DataFrame({'restaurant':['Freddys', 'Freddys', 'Jumpin Java', 'Freddys', 'Jumpin Java', 'Caffe Low', 'Kitchen 2'], 
                    'customer': ['John', 'John', 'Paula', 'John', 'Justin', 'Paula', 'Paula'], 
                    'date':['1-1-17', '1-2-17', '1-3-17', '1-4-17', '1-5-17', '1-6-17', '1-7-17']})

  customer    date   restaurant
0     John  1-1-17      Freddys
1     John  1-2-17      Freddys
2    Paula  1-3-17  Jumpin Java
3     John  1-4-17      Freddys
4   Justin  1-5-17  Jumpin Java
5    Paula  1-6-17    Caffe Low
6    Paula  1-7-17    Kitchen 2

Create函数返回指定的条件。你知道吗

def get_eating_pattern(df):
    for name in df.customer.unique():
        three_visits = 0
        total_visits = 0
        unique_rests = 0

        three_visits = df.loc[df['customer'] == name]['restaurant'].value_counts()[0]
        if '3' in str(three_visits):
            print(name, 'went to the same restaurant 3 times.')

        total_visits = df.loc[df['customer'] == name]['restaurant'].value_counts().sum()
        unique_rests = df.loc[df['customer'] == name]['restaurant'].nunique()

        if total_visits == 3 & unique_rests == 3:
            print(name, 'went to 3 different restaurants.')

测试函数以确保它与基于df的内容所期望的匹配。你知道吗

>>> get_eating_pattern(df=df)
John went to the same restaurant 3 times.
Paula went to 3 different restaurants.

使用Berry py的设置:

df = pd.DataFrame({'restaurant':['Freddys', 'Freddys', 'Jumpin Java', 'Freddys', 'Jumpin Java', 'Caffe Low', 'Kitchen 2'], 
                    'customer': ['John', 'John', 'Paula', 'John', 'Justin', 'Paula', 'Paula'], 
                    'date':['1-1-17', '1-2-17', '1-3-17', '1-4-17', '1-5-17', '1-6-17', '1-7-17']})

df_out = df.groupby('customer').agg({'customer':'size','restaurant':'nunique'}).rename(columns={'customer':'Num_Visits','restaurant':"Num_Restaurants"})

df_out.query('Num_Visits >= 3')

输出:

         Num_Visits  Num_Restaurants
customer                             
John               3                1
Paula              3                3

相关问题 更多 >