我有一个包含年度季度(例如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')
在我看到的第一季度'这似乎并没有起作用。在一些已经完成的预订之后。
答案 0 :(得分:1)
您需要指定用于获取第一个值的列:
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]})
下面,我将文本区(例如'2010-Q1')转换为数字等效项,方法是将第一个字符的int值转换为字符(df.Year_Quarter.str[:4].astype(int)
)。然后我将它乘以4并添加该季度的值。此值仅用于差分以确定自第一个订单以来的总季度数。
接下来,我在transform
上使用groupby
来获取我们刚刚计算的这些季度的最小值。使用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
答案 1 :(得分:0)
第1部分:
我认为你需要稍微改变一下才能得到你想要的结果:
alldata.sort_values(by=['Customer_ID', 'Year_Quarter',
'Total_Apps_Reseller_Bookings_USD'],
ascending=[1, 1],inplace=True)
first_q = alldata[['Customer_ID','Year_Quarter']].groupby(by='Customer_ID').head(1)
第2部分:
继续关闭第1部分,您可以将值重新合并到原始数据帧。此时,您可以编写自定义函数来减去日期字符串,然后将其应用于每一行。
类似的东西:
def qt_sub(val, first):
year_dif = val[0:4] - first[0:4]
qt_dif = val[6] - first[6]
return 4 * int(year_dif) + int(qt_dif)
alldata['diff_from_first'] = alldata.apply(lambda x: qt_sub(x['Year_Quarter'],
x['First_Sale']),
axis=1)