python - 查找数据框中第一次出现的值

标签 python pandas

我有一个包含年季度(例如 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]})

下面,我将文本季度(例如“2010-Q1”)转换为数字等价物,方法是采用字符的第一个整数值 (df.Year_Quarter.str[:4].astype(int))。然后我将它乘以四并加上季度的值。此值仅用于差分以确定自第一个订单以来的季度总数。

接下来,我在 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

关于python - 查找数据框中第一次出现的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34281260/

相关文章:

Python (Pandas) - 删除带有 NA 的行并将值转换为 bool 值

python - Django 中的 "Master page"管理

python - matplotlib 颜色线由 "value"

python - 填写两个列表之间的范围

python - 如何将矩阵转换为 Pandas 数据框

python - 在 pandas DataFrame 内的列表上使用 numpy.where (或 numpy.select)

python - 如何使用下面两个单元格的值更新数据帧单元格的值?

Python + OpenCV : Enumerate Matrix

python - `Pandas argmax` 在屏蔽后获取所有 `True` 索引(Python 3)(例如 (pd.Series > 0).argmax()))

python - OS X cmake 找不到 PythonLibs 3.4