I am a 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 change with Z. But also, I need to add 1 in the last character
For instance.
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