Search code examples
pythonpython-3.xpandasalphanumeric

How to fill an alphanumeric series in a column in a pandas dataframe?


I have certain pandas dataframe which has a structure like this

A    B    C

1    2    2
2    2    2 
...

I want to create a new column called ID and fill it with an alphanumeric series which looks somewhat like this

ID       A    B    C

GT001    1    2    2
GT002    2    2    2 
GT003    2    2    2 
...

I know how to fill it with either alphabets or numerals but I couldn't figure out if there is a "Pandas native" method which would allow me to fill an alphanumeric series.What would be the best way to do this?


Solution

  • Welcome to Stack Overflow!

    If you want a custom ID, then you have to create a list with the desired index:

    list = []
    
    for i in range(1, df.shape[0] + 1): # gets the length of the DataFrame.
        list.append(f'GT{i:03d}') # Using f-string for format and 03d for leading zeros.
    
    df['ID'] = list
    

    And if you want to set that as an index do df.set_index('ID', inplace=True)