python – 第一次在数据帧中查找值

我有一个包含年度季度(例如2015-Q4)的数据框,customer_ID和预订金额,以及许多其他列目前无关紧要.我想创建一个每个客户第一次预订的列.我试过这个:

alldata.sort_values(by=['Total_Apps_Reseller_Bookings_USD', 'Year_Quarter'], 
                    ascending=[1, 1], 
                    inplace=True)
first_q = alldata[['Customer_ID', 'Year_Quarter']].groupby(by='Customer_ID').first()

但我不确定它是否奏效.

此外,我想要另一个专栏,告诉我第一次预订后预订了多少个季度.我没有使用替换和字典,所以我使用了合并.我为每个预订季度创建一个数字ID,从上面创建第一个季度,然后减去这两个:

q_booking_num = pd.DataFrame({'Year_Quarter': x, 'First_Quarter_id': np.arange(28)})

alldata = pd.merge(alldata, q_booking_num, on='Year_Quarter', how='outer')
q_first_num = pd.DataFrame({'First_Quarter': x, 'First_Quarter_id': np.arange(28)})
alldata = pd.merge(alldata, q_first_num, on='First_Quarter', how='outer')

这看起来根本不起作用,因为我看到已经做出一些预订后的“第一季度”.

最佳答案 您需要指定用于获取第一个值的列:

first_q = (alldata[['Customer_ID','Year_Quarter']]
           .groupby(by='Customer_ID')
           .Year_Quarter
           .first()
          )

以下是三位客户的一些示例数据:

df = pd.DataFrame({'customer_ID': [1, 
                                   2, 2, 
                                   3, 3, 3], 
                   'Year_Quarter': ['2010-Q1', 
                                    '2010-Q1', '2011-Q1', 
                                    '2010-Q1', '2011-Q1', '2012-Q1'], 
                   'Total_Apps_Reseller_Bookings_USD': [1, 
                                                        2, 3, 
                                                        4, 5, 6]})

下面,我通过获取第一个字符的int值(df.Year_Quarter.str [:4] .astype(int))将文本区(例如’2010-Q1′)转换为数字等价物.然后我将它乘以4并添加该季度的值.此值仅用于差分以确定自第一个订单以来的总季度数.

接下来,我使用groupby上的transform来获取我们刚刚计算出的这些季度的最小值.使用transform将此值保持为与原始数据帧相同的形状.

然后我将quarters_since_first_order计算为季度和第一季度之间的差异.

df['quarters'] = df.Year_Quarter.str[:4].astype(int) * 4 + df.Year_Quarter.str[-1].astype(int)
first_order_quarter_no = df.groupby('customer_ID').quarters.transform(min)
df['quarters_since_first_order'] = quarters - first_order_quarter_no
del df['quarters']  # Clean-up.

>>> df
   Total_Apps_Reseller_Bookings_USD Year_Quarter  customer_ID  quarters_since_first_order
0                                 1      2010-Q1            1                           0
1                                 2      2010-Q1            2                           0
2                                 3      2011-Q1            2                           4
3                                 4      2010-Q1            3                           0
4                                 5      2011-Q1            3                           4
5                                 6      2012-Q1            3                           8
点赞