Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.3k views
in Technique[技术] by (71.8m points)

python - "Add" number to the string inside pandas series

Suppose I have the following series(type is string)

0      F0/Images/1/15.tiff
1      F0/Images/1/15.tiff
2      F0/Images/1/15.tiff
3      F0/Images/1/15.tiff
4      F0/Images/1/15.tiff

I want to "add" +1 to the number just before '.tiff'. So I should get a result:

0      F0/Images/1/16.tiff
1      F0/Images/1/16.tiff
2      F0/Images/1/16.tiff
3      F0/Images/1/16.tiff
4      F0/Images/1/16.tiff

How can I do it in pandas?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can achieve this with a regex.

We can define a function to perform these and then apply it to our column.

df
   idx             filename
0    0  F0/Images/1/15.tiff
1    1  F0/Images/1/15.tiff
2    2  F0/Images/1/15.tiff
3    3  F0/Images/1/15.tiff
4    4  F0/Images/1/15.tiff


def add_one(filename):
    number = int(re.search(r'(?<=/)[0-9]{2}(?=.tiff)', filename).group()) + 1
    return re.sub(r'(?<=/)[0-9]{2}(?=.tiff)', str(number), filename)

df['filename'] = df['filename'].apply(add_one)

df
   idx             filename
0    0  F0/Images/1/16.tiff
1    1  F0/Images/1/16.tiff
2    2  F0/Images/1/16.tiff
3    3  F0/Images/1/16.tiff
4    4  F0/Images/1/16.tiff

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...