I don't know how you have tested it the first time, here is my logic. It supposes the first element in flag is 0!

df = pd.DataFrame({'memberid': [1]*11,
                   'flag': [0,0,1,1,0,1,0,0,0,1,1],
                   })
df['seq'] = ""
for i in range(0, len(df)):
    df.loc[i, 'seq'] = 1 if df.loc[i, 'flag'] == 0 else  df.loc[i - 1, 'seq'] + 1
print(df)

Another solution using lambda:

df = pd.DataFrame({'memberid': [1] * 11,
                   'flag': [0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1]
                   })

def f(flag):
    global previous_seq
    previous_seq = 1 if flag == 0 else previous_seq + 1
    return previous_seq

previous_seq = 0
df['seq'] = df[['flag']].apply(lambda x: f(*x), axis=1)
print(df)

I am not sure if it is faster than the first solution....

Answer from Frenchy on Stack Exchange
🌐
Dbmstutorials
dbmstutorials.com › pyspark › spark-dataframe-sequence-number.html
PySpark: Dataframe Sequence Number
Example 3: When there are multiple partition then it will generate consecutive numbers only within same partition. from pyspark.sql.functions import monotonically_increasing_id, spark_partition_id df.rdd.getNumPartitions() # 1 df = df.repartition(4) df.rdd.getNumPartitions() #4 df_update = df.withColumn("seq_num", monotonically_increasing_id()).withColumn("partition#", spark_partition_id()) df_update.show() +-----+---------+-------+-----------+----------+ |db_id| db_name|db_type| seq_num|partition#| +-----+---------+-------+-----------+----------+ | 22| Mysql| null| 0| 0| | 12| Teradata| RDBMS| 1| 0| | 51| null|CloudDB| 8589934592| 1| | 15| Vertica| RDBMS| 8589934593| 1| | 14|Snowflake|CloudDB|17179869184| 2| | 50|Snowflake| RDBMS|25769803776| 3| | 12| Teradata| RDBMS|25769803777| 3| +-----+---------+-------+-----------+----------+
Top answer
1 of 4
2

I don't know how you have tested it the first time, here is my logic. It supposes the first element in flag is 0!

df = pd.DataFrame({'memberid': [1]*11,
                   'flag': [0,0,1,1,0,1,0,0,0,1,1],
                   })
df['seq'] = ""
for i in range(0, len(df)):
    df.loc[i, 'seq'] = 1 if df.loc[i, 'flag'] == 0 else  df.loc[i - 1, 'seq'] + 1
print(df)

Another solution using lambda:

df = pd.DataFrame({'memberid': [1] * 11,
                   'flag': [0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1]
                   })

def f(flag):
    global previous_seq
    previous_seq = 1 if flag == 0 else previous_seq + 1
    return previous_seq

previous_seq = 0
df['seq'] = df[['flag']].apply(lambda x: f(*x), axis=1)
print(df)

I am not sure if it is faster than the first solution....

2 of 4
2

I've tried this 3 ways iterating through the flags (counting the continuous 1s) and this was the fastest for the same dataframe (large enough to neglect small variation in time on retries).

I'm maintaining two lists (one for flag, one for seq) and a counter variable.

We loop through flags and append the corresponding seq to seq_list. As you described, we keep track of count if we keep seeing 1 and reset to 1 if we see a 0 in the flags_list.

We add seq_list as a column to the dataframe once we're done.

seq_list = []
counter = 0
flag_list = list(df['flag'])
for flag in flag_list:
    if(flag == 0):
        counter = 1
        seq_list.append(counter)
    else:
        counter += 1
        seq_list.append(counter)
        
df['seq'] = seq_list

Other variants I tried include

  • Directly iterating through each flag element in the dataframe (using .loc) and adding to the seq_list which gets added as a column but this took 16x of the time for the method above.
seq_list = []
counter = 0

for i in range(df.shape[0]):
    if(df.loc[i,'flag'] == 0):
        counter = 1
        seq_list.append(counter)
    else:
        counter += 1
        seq_list.append(counter)
        
df['seq'] = seq_list
  • Directly iterating through each flag element in the dataframe (using .loc) and modifying the dataframe right away (again, using .loc) but this was even slower and took 5x-10x the time for the previous method.
counter = 1
df['seq'] = 0

for i in range(df.shape[0]):
    if(df.loc[i,'flag'] == 0):
        counter = 1
        df.loc[i,'seq'] = counter
    else:
        counter += 1
        df.loc[i,'seq'] = counter
🌐
Stack Overflow
stackoverflow.com › questions › 72616994 › numbering-sequences-in-pandas
python - Numbering Sequences in pandas - Stack Overflow
df['Numbered'] = ((df['Steps'] & ~df['Steps'].shift(fill_value=False)).cumsum() .where(df['Steps'], 0)) print (df) Steps Numbered 0 True 1 1 False 0 2 True 2 3 True 2 4 True 2 5 False 0 6 True 3 7 True 3 8 False 0 9 False 0 10 False 0 11 True 4 ... import numpy as np import pandas as pd steps = ['false','false','true','true','true', 'false','true','true','false','false','true'] data = pd.DataFrame({"steps":steps}) numbred =[] c = 0 for i in range(len(data.index)): if data['steps'][i] == 'false': numbred.append(0) if data['steps'][i+1] == 'true': c += 1 else: numbred.append(c) data = pd.DataFrame({"steps":steps,'numbred':numbred}) print(data)
People also ask

How to add a sequential number to each row within a group in pandas
ANS: Use the .groupby() method followed by .cumcount() to get a zero-based index for each group, and add 1 if you need a one-based index. For example: df['sequence'] = df.groupby('group_column').cumcount() + 1.
🌐
sqlpey.com
sqlpey.com › python › sequential-numbering-by-group-in-pandas
Sequential Numbering by Group in Pandas DataFrames - sqlpey
Is there a way to concatenate values within groups as a sequence
ANS: Yes, after sorting by relevant columns, use .groupby() with an .aggregate() function that joins the values, such as '-'.join(tuple(x)). For example: df.groupby('group_col')['value_col'].aggregate(lambda x: '-'.join(tuple(x))).
🌐
sqlpey.com
sqlpey.com › python › sequential-numbering-by-group-in-pandas
Sequential Numbering by Group in Pandas DataFrames - sqlpey
Can I create a sequence based on a specific order within groups
ANS: Yes, sort your DataFrame by the desired columns (including the grouping columns and the ordering column) first, then apply .groupby().cumcount(). For instance, df.sort_values(by=['group_col', 'order_col']) followed by df.groupby('group_col').cumcount().
🌐
sqlpey.com
sqlpey.com › python › sequential-numbering-by-group-in-pandas
Sequential Numbering by Group in Pandas DataFrames - sqlpey
🌐
sqlpey
sqlpey.com › python › sequential-numbering-by-group-in-pandas
Sequential Numbering by Group in Pandas DataFrames - sqlpey
July 22, 2025 - import pandas as pd data = {'col': ['A', 'B', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'A']} df = pd.DataFrame(data) # Add a sequence count for each group in 'col' starting from 1 df['counts'] = df.groupby('col').cumcount() + 1 print("DataFrame with sequence counts:") print(df) This is a clean way to get a running count for each distinct value in a specified column. When the order of rows within a group matters for the sequence generation, explicitly sorting the DataFrame before applying groupby().cumcount() is crucial.
🌐
MetaProgrammingGuide
metaprogrammingguide.com › code › how-to-generate-sequence-number-in-python
Python, How to generate sequence number in python
July 9, 2022 - Use the Python range() Function to Generate Sequences of Numbers. In Python, range is an immutable sequence type, meaning it's a class that generates a sequence of numbers that cannot be modified.
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 69745678 › create-sequences-from-pandas-dataframe
python - Create sequences from pandas DataFrame - Stack Overflow
October 27, 2021 - def generate_sequence(sequence1, sequence2, sequence3): new_sequence = [] # Генерираме втората поредица for i in range(len(sequence1)): if i == 0: new_sequence.append(sequence1[i]) else: new_sequence.append(sequence1[i] + sequence2[i - 1]) # Генерираме третата поредица for i in range(len(sequence2)): if i == 0: new_sequence.append(sequence1[i] + sequence2[i]) else: new_sequence.append(sequence2[i] - sequence2[i - 1]) # Генерираме четвъртата поредица for i in range(len(sequence3)): if i == 0: new_sequence.append(seque
🌐
Medium
medium.com › @vashishtarora2008 › adding-increasing-ids-in-a-dataframe-rdd-with-pandas-and-usecases-included-b9b091927b9e
Adding increasing id’s/sequence in a spark dataframe/rdd (with pandas and usecases included) | by Vashisht arora | Medium
January 31, 2023 - Cons of this method 1) Converting to rdd and converting it back to dataframe can be an expensive operation. 2) Also this method has an added overhead of getting the specific column values. ... These allow developers to debug the code during the runtime which was not allowed with the RDDs. ... Assigns a unique, sequential number to each row, starting with one, according to the ordering of rows within the window partition.
🌐
Wordpress
aprakash.wordpress.com › 2020 › 12 › 20 › sequential-counter-with-groupby-pandas-dataframe
Sequential counter with groupby – Pandas DataFrame | Learn. Share. Repeat.
December 21, 2020 - The transaction sequence order ranking for Marie is not correct in this case. To achieve this you can use Pandas groupby.cumcount(). It numbers each item in each group from 0 to the length of that group – 1.
🌐
Stack Overflow
stackoverflow.com › questions › 51916916 › how-to-create-sequence-in-pandas-dataframe
python - How to create sequence in pandas dataframe? - Stack Overflow
August 19, 2018 - df = pd.DataFrame({'User': ['A','A','A','A','B','B','B', 'B'], 'touchpoint': ['C1', 'C2', 'C1', 'C4', 'C2', 'C1', 'C1', 'C1'], 'conversion': [0,0,0,1,0,0,0,1]}) df1 = df.groupby(['User']).aggregate(lambda x: list(x)) df1 = df1.apply(lambda x: "".join([x[1][i] + '*' if value else x[1][i] + '>' for i, value in enumerate(x[0])]), axis = 1) df1 = df1.apply(lambda x: x.split('*')[:-1])