如何总结熊猫数据框

时间:2020-10-16 19:31:42

标签: python pandas dataframe

我有一个熊猫数据框,其中包含约20,xxx条公交车登机记录。数据集包含一个cardNumber字段,该字段对于每个乘客都是唯一的。有一个type字段,用于标识登机类型。有routeName列指定登机的路线,最后是Date列,用于标识登机的时间。我在下面提供了一个模拟数据框。

df = pd.DataFrame(
    {'cardNumber': ['999', '999', '999', '999', '901', '901', '888', '888'],
     'type': ['trip_pass', 'transfer', 'trip_pass', 'transfer', 'stored_value', 'transfer', 'trip_pass', 
              'trip_pass'],
     'routeName': ['1', '2', '2', '1', '20', '3', '4', '4'],
     'Date': ['2020-08-01 06:18:56 -04:00', '2020-08-01 06:46:12 -04:00', '2020-08-01 17:13:51 -04:00',
              '2020-08-01 17:47:32 -04:00', '2020-08-10 15:23:16 -04:00', '2020-08-10 15:44:45 -04:00',
              '2020-08-31 06:54:09 -04:00', '2020-08-31 16:23:41 -04:00']}
)
df['Date'] = pd.to_datetime(df['Date'])

我想做的是总结转让活动。从路线1到路线2或从路线2到路线1平均发生了多少次转移。数据集中有11条不同的路线可能在这两者之间发生转移。

我希望输出看起来像(请注意,下面的输出不是从上面提供的示例中生成的):

From   |   To     |   Avg. Daily
----------------------------------
 1     |   2      |     45.7
 1     |   3      |     22.6
 20    |   1      |     12.2 

2 个答案:

答案 0 :(得分:1)

以下代码适用于您提供的块数据。如果在您的实际数据中不起作用,请告诉我。可能有更好的方法可以做到这一点,但我认为这是一个很好的起点。

这里的总体思路是按乘客分组以找出路线。然后,由于您需要每日平均值,因此需要按日期分组,然后按目的地分组才能计算每日平均值。

# Define a function to get routes' relationship (origin vs destination)
def get_routes(x):
    if 'transfer' not in x.type.tolist(): # if no 'transfer' type in group, leave it as 0 (we'll remove them afterwards)
        return 0
    x = x[x.type == 'transfer'] # select target type
    date = df[df.cardNumber=='999'].Date.dt.strftime('%m/%d/%Y').unique()
    if date.size == 1: # if there is more than one date by passenger, you'll need to change this code
        date = date[0]
    else:
        raise Exception("There are more than one date per passenger, please adapt your code.")
    s_from = x.routeName[x.Date.idxmin()] # get route from the first date
    s_to = x.routeName[x.Date.idxmax()] # get route from the last date
    return date, s_from, s_to

# Define a function to get the routes' daily average
def get_daily_avg(date_group):
    daily_avg = (
        date_group.groupby(['From', 'To'], as_index=False) # group the day by routes
        .apply(lambda route: route.shape[0] / date_group.shape[0]) # divide the total of trips of that route by the total trips of that day
    )
    return daily_avg

# Get route's relationship
routes_series = df.groupby('cardNumber').apply(get_routes) # retrive routes per passenger
routes_series = routes_series[routes_series!=0] # remove groups without the target type

# Create a named dataframe from the series output
routes_df = pd.DataFrame(routes_series.tolist(), columns=['Date', 'From', 'To'])

# Create dataframe, perform filter and calculations
daily_routes_df = (
    routes_df.query('From != To') # remove routes with same destination as the origin
    .groupby('Date').apply(get_daily_avg) # calculate the mean per date
    .rename(columns={None: 'Avg. Daily'}) # set name to previous output
    .drop(['From','To'], axis = 1) # drop out redundant info since there's such info at the index
    .reset_index() # remove MultiIndex to get a tidy dataframe
)

# Visualize results
print(daily_routes_df)

输出:

         Date From To  Avg. Daily
0  08/01/2020    2  1         1.0

这里,平均值是1,因为每个组只有一个计数。请注意,仅考虑了“传输”类型。没有它的人,或者没有改变路线的人,被进一步删除。

答案 1 :(得分:0)

如果我提出的问题正确,那么您想确定行程的起点和终点,并且第一个事件与起点(路线名称)相对应,然后计算数据中的门票数量具有相同起点和终点的设置。

如果是这样,您可以按照以下步骤进行操作

# srot the dataframe so you can use first/last
df_sorted= df.sort_values(['cardNumber', 'Date']).reset_index(drop=True)

# calculate the counts do the counts, but only
# from the defined types
indexer_trip_points= df_sorted['type'].isin(['transfer'])
df_from_to= df_sorted[indexer_trip_points].groupby('cardNumber').agg(
                  start_date=('Date', 'first'),
                  trip_start=('routeName', 'first'), 
                  trip_end=('routeName', 'last'),
)
                      
df_from_to['start_date']= df_from_to['start_date'].dt.date
df_counts= df_from_to.groupby(['trip_start', 'trip_end', 'start_date']).agg(
    count=('trip_start', 'count')
)
df_counts.reset_index(drop=False, inplace=True)
df_counts.groupby(['trip_start', 'trip_end']).agg(
    avg=('count', 'mean')
)

结果是:

                     avg
trip_start trip_end     
2          1           1
3          3           1

您会注意到,最后一个条目的起点与端点相同。因此,可能您需要过滤出行程,而您还没有完整的数据。例如。如果您的路线永远不会以开始时的相同路线名结尾,则只需比较两列即可对其进行过滤。