擅长:python、mysql、java
<p>好吧,我已经弄明白了。首先,我们创建一个事务字段,其中包含要求和的个数:</p>
<pre><code>df["Trans"] = len(df)*[1]
</code></pre>
<p>我们按客户分组:</p>
<pre><code>cust_gp = df.groupby("Customer")
</code></pre>
<p>第一个最简单:</p>
<pre><code>cust_gp.sum()
</code></pre>
<p>四也不难:</p>
<pre><code>cust_gp.max()
</code></pre>
<p>2号和3号很棘手。。。我找到了一个解决方案,似乎与我的测试数据。按客户和日期对数据进行排序,然后按每个客户的第一个进行聚合:</p>
<pre><code>df.sort(["Customer","Date"]).groupby("Customer").first()
df.sort(["Customer","Date"]).groupby("Customer").last()
</code></pre>
<p>…但是当我在我的大数据集上运行它时,我被告知我最近的一些事务发生在上一次事务之前。这毫无意义。你知道吗</p>
<p>原来日期字段是作为文本导入的!所以,完整的解决方案:</p>
<pre><code>df.Date = pd.to_datetime(df.Date) # Date field should be date, not text
df = df.sort(["Customer","Date"])
cust_gp = df.groupby("Customer")
total_df = cust_gp.sum() # 1
largest_df = cust_gp.max() # 2
first_df = cust_gp.first() # 3
last_df = cust_gp.last() # 4
</code></pre>
<p>我对此很满意,除了“礼物”一栏,我确信这不是以最优雅的方式实现的。你知道吗</p>