简体   繁体   中英

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?

import pandas as pd
import numpy as np

df = pd.DataFrame({'player': np.linspace(0,20,20)})

n = 21
data = ['GT' + '0'*(3-len(str(i))) + str(i) for i in range(1, n)]
df['ID'] = data

       player     ID
0    0.000000  GT001
1    1.052632  GT002
2    2.105263  GT003
3    3.157895  GT004
4    4.210526  GT005
5    5.263158  GT006
6    6.315789  GT007
7    7.368421  GT008
8    8.421053  GT009
9    9.473684  GT010
10  10.526316  GT011
11  11.578947  GT012
12  12.631579  GT013
13  13.684211  GT014
14  14.736842  GT015
15  15.789474  GT016
16  16.842105  GT017
17  17.894737  GT018
18  18.947368  GT019
19  20.000000  GT020

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM