Home > Back-end >  Is there any way to change all values in a column in pandas?
Is there any way to change all values in a column in pandas?

Time:07-28

have a pandas data frame, which has values for example from ID:ko00001 to ID:ko99999.

How could I change these values to 00001-99999? And convert to integer?

CodePudding user response:

If the length of the String is the same(ID:koxxxxx) you can use a lambda function to get the last 5 chars of this string and then convert it to int:

X = pd.DataFrame({
        'old':["ID:ko00001","ID:ko12345",'ID:ko99999']})

X['new'] = X.apply(lambda x: int(x[0][5:10]),axis=1)
print(X)

Output:

          old    new
0  ID:ko00001      1
1  ID:ko12345  12345
2  ID:ko99999  99999

p.s when asking this kind of questions add an example of an input and output to your question...

CodePudding user response:

A vectorized option would be:

df['col'].str[-5:].astype(int)
print(df)

Result

0        1
1    99999
  • Related