I am starting with Python. I need to replace the strings from 'Old' column basis on a condition. If the first character of the string is A
I need to replace it with Z
, but I also need to add 1 to value of the last character
For example:
Old | New |
---|---|
A2 | Z3 |
C4 | C4 |
B4 | B4 |
A5 | Z6 |
A1 | Z2 |
df = pd.DataFrame({'Old': ['A2', 'C4', 'B4', 'A5'], 'New': ['Z3', 'C4', 'B4', 'Z6']})
df['New'] = df['Old'].str.replace('A','Z')
CodePudding user response:
Use a custom function:
df['New'] = df['Old'].apply(lambda x: x if x[0] != 'A' else f'Z{int(x[1:]) 1}')
print(df)
# Output:
Old New
0 A2 Z3
1 C4 C4
2 B4 B4
3 A5 Z6