Home > Software engineering >  Add value to column data of dataFrame in Pandas
Add value to column data of dataFrame in Pandas

Time:12-13

I have a dataFrame like this:

>>> data = {'Section':['300/18','2‐ 350/24','400/30']}
>>> df = pd.DataFrame(data)
>>> df
     Section
0     300/18
1  2‐ 350/24
2     400/30

I want to add 50 to the value just before /. So the new dataFrame will be like this:

     Section
0     350/18
1  2‐ 400/24
2     450/30

I know we can for loop the column 'Section', then split the string by '/', then add 50 to the former value, then reformat the string and assign to the cell. Assuming it might have hundred thousand rows, I am wondering if there is more efficient method to do it.

CodePudding user response:

One approach would be to use str.replace with the replacement lambda function to substitute the new values:

repl =  lambda g: f'{int(g.group(1))   50}/'
df['Section'] = df['Section'].str.replace(r'(\d )/', repl, regex=True)

     Section
0     350/18
1  2‐ 400/24
2     450/30
  • Related