1

I would like to ask for a little help.

I have a frame consisting of multiple columns, here in this case I just highlighted three columns, which are important for me

frame=pd.DataFrame({"String":["000111222f12","000121222f11","000131222f12","000141222f12"],"Cavity": ["Cav 2", "Cav 1", "Cav 1", "Cav 2"]})

   Cavity     String  
0  Cav 2  011121222f12              
1  Cav 1  011111222f14              
2  Cav 2  011111222f16              
3  Cav 2  000111222f17   

What I would like to get is the following: Based on cavity column, I need to change the 4.location (counting at zero) for the string, meaning if I have Cav 2 I should have 011121222f16

The desired solution should look like this

   Cavity     String      Corrected String
0  Cav 2  011121222f12    011121222f12            
1  Cav 1  011111222f14    011111222f14            
2  Cav 2  011111222f16    011121222f16            
3  Cav 2  000111222f17    000121222f17 

I tried to solve it with a combination of replace and slicing the string at the specific location and using np.where, but without success.

Any advice for me?

Cheers and thanks

1
  • Is necessary extract number and use for correct data? Or only replace Cav 2 to 2 ? Commented Oct 13, 2020 at 10:48

5 Answers 5

2

Try this:

frame['Corrected String'] = frame['String'].str[:4] + frame['Cavity'].str.split().str[-1] + frame['String'].str[5:]
Sign up to request clarification or add additional context in comments.

1 Comment

thanks mate exactly what I was looking for. Solved it by a work around but this is defintley the solution I needed :)
1

Here's an alternative way. You can use re.sub to substitute the string between 2 capture groups:

import re

frame['Corrected_String'] = [re.sub(r'^(.{4}).(.*)$', fr'\g<1>{c[-1]}\g<2>', s)
                             for s, c in zip(frame['String'], frame['Cavity'])]

[out]

         String Cavity Corrected_String
0  000111222f12  Cav 2     000121222f12
1  000121222f11  Cav 1     000111222f11
2  000131222f12  Cav 1     000111222f12
3  000141222f12  Cav 2     000121222f12

Explanation

the pattern parameter here is the regex pattern '^(.{4}).(.*)$'.

  • ^ is the beginning of the string
  • (.{4}) - this is the first capture group (\g<1>), denoting the first 4 characters of the string.
  • . - this is the fifth character in the string, ultimately the character that we'll replace.
  • (.*)$ - this is the 2nd capture group (\g<2>), denoting all remaining characters up to the end of the string ($)

the repl parameter here is the replacement string fr'\g<1>{c[-1]}\g<2>'.

  • \g<1> the first capture group (first 4 characters)
  • Since we're using f-string notation, {c[-1]} will be evaluated as the last character of the Cavity value.
  • \g<2> - the 2nd capture group (all remaining characters)

Comments

0

You can extract integer from Cavity column and add after 4.position:

s = frame['Cavity'].str.extract('(\d+)', expand=False)
frame['Corrected'] = frame['String'].str[:4] + s + frame['String'].str[5:]
print (frame)
         String Cavity     Corrected
0  000111222f12  Cav 2  000121222f12
1  000121222f11  Cav 1  000111222f11
2  000131222f12  Cav 1  000111222f12
3  000141222f12  Cav 2  000121222f12

Comments

0

I would do it following way:

import pandas as pd
frame=pd.DataFrame({"String":["000111222f12","000121222f11","000131222f12","000141222f12"],"Cavity":  ["Cav 2", "Cav 1", "Cav 1", "Cav 2"]})
frame['Corrected'] = frame['String'].str[:4] + frame['Cavity'].str.strip('Cav ') + frame['String'].str[5:]
print(frame)

Output:

         String Cavity     Corrected
0  000111222f12  Cav 2  000121222f12
1  000121222f11  Cav 1  000111222f11
2  000131222f12  Cav 1  000111222f12
3  000141222f12  Cav 2  000121222f12

Comments

0

not faster but maybe clearer and reusable

def replace_nth_char(chaine: str, pos: int, value: str) -> str:
    """replace character in string at given position"""
    a = list(chaine)
    a[pos] = value
    return "".join(a)


frame.loc[:, "Corrected"] = frame.apply(lambda row: replace_nth_char(row["String"], 4, row["Cavity"][-1]), axis=1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.