A customer can appear on several rows of an event log. To label those rows as that customer’s first, second, and third recorded appearances, use groupby().cumcount() and add one.

The example below numbers six events without moving or removing any of them. The counter follows the current input order, so C01 receives 1, 2, and 3 even though other customers appear between its rows.

Six event rows stay in input order while customer C01 receives positions 1, 2, and 3, customer C02 receives 1 and 2, and customer C03 receives 1.
The position counter restarts for each customer. These six fictional events retain their original row order.Credit: MathBlog

Start with a log in the order you want to number

Each row in this fictional log represents one event. The event ID identifies the source record; the customer ID tells us which counter to use. Here, the export’s row order is the order we want to label.

Six fictional events in their original input order.
Event Customer
E01 C01
E02 C02
E03 C01
E04 C03
E05 C02
E06 C01

The first C01 row and the first C02 row should both receive 1. A single column of numbers from 1 through 6 would count positions in the whole table rather than positions within each customer.

Add a counter that restarts for each customer

Run this complete block in a Python session with pandas installed. The function copies its input and rejects missing or blank customer keys before numbering.

import pandas as pd

events = pd.DataFrame({
    "event": ["E01", "E02", "E03", "E04", "E05", "E06"],
    "customer": pd.Series(
        ["C01", "C02", "C01", "C03", "C02", "C01"], dtype="string"
    ),
})

def number_customer_rows(frame):
    result = frame.copy()
    keys = result["customer"].astype("string")
    if keys.isna().any() or keys.str.strip().eq("").any():
        raise ValueError("Every row needs a nonblank customer key.")
    result["row_in_customer"] = (
        result.groupby("customer", sort=False).cumcount() + 1
    )
    return result

numbered = number_customer_rows(events)
print(numbered.to_string(index=False))

Output:

event customer  row_in_customer
  E01      C01                1
  E02      C02                1
  E03      C01                2
  E04      C03                1
  E05      C02                2
  E06      C01                3

cumcount() begins at zero inside each group. Adding one gives the displayed sequence 1, 2, 3, and so on. The result aligns with the original rows, so it can be assigned directly as a new column.

sort=False leaves group keys in their order of appearance. It does not sort the events within a customer. C01’s rows remain E01, E03, and E06, and all six source rows stay in the result.

Read a row number as a position

E03 has row_in_customer equal to 2 because it is the second C01 row encountered. It is the third row of the whole table. E04 gets 1 because it is the first C03 row, even though three other events precede it.

The final counter for C01 is 3, matching its three source rows. C02 has two rows and C03 has one. Repeated customer labels are expected here; deleting them would remove real events.

This is also a different question from selecting the largest rows in each group. A position counter does not compare sales, scores, or another measured value. Equal measurements would still receive separate positions because they occupy separate rows.

Choose the order before calling the function

If you need a customer’s first event by time, parse the timestamps and sort by the event-time column before numbering. Add a reliable tie-breaking field when two events share a time. The input order used here does not prove which event happened first.

A stable sort can retain input order among equal sort values, but it cannot tell you which of two simultaneous records should come first. Use the source system’s sequence rule when the distinction matters. Do not sort an arbitrary event ID and assume that its alphabetical order is chronological.

Keep the original event ID after adding the counter. Inserting an earlier row or changing the sort order can change later sequence numbers. Treating the pair of customer and row number as a permanent identifier would make those changes hard to track.

Review missing keys without combining unknown customers

The validation uses isna() for missing markers and a whitespace check for blank text. It does not rewrite the customer IDs. If padded or differently capitalized IDs need cleanup, decide that rule separately and retain the originals.

The function stops on a missing customer because several unknown labels do not necessarily identify the same person. pandas can include missing keys in a group when requested, but grouping them together is a data decision, not evidence of shared identity. For more on blank strings and missing markers, see finding and filling missing values in pandas.

The complete example was executed with Python 3.11.3 and pandas 2.3.3. Check the first and last numbered rows for a few customers against your source log before using the column in a report.

Further reading