Take the below example. To replace one string in one particular column I have done this and it worked fine:
df = pd.DataFrame({'key': ['A', 'B', 'C', 'A', 'B', 'C'],
'data1': range(6),
'data2': ['A1', 'B1', 'C1', 'A1', 'B1', 'C1']},
columns = ['key', 'data1', 'data2'])
key data1 data2
0 A 0 A1
1 B 1 B1
2 C 2 C1
3 A 3 A1
4 B 4 B1
5 C 5 C1
df['data2']= df['data2'].str.strip().str.replace("A1","Bad")
key data1 data2
0 A 0 Bad
1 B 1 B1
2 C 2 C1
3 A 3 Bad
4 B 4 B1
5 C 5 C1
Q(1) How can we conditionally replace one string? Meaning that, in column data2, I would like to replace A1 but only if "key==A" and "data1">1. How can I do that?
Q(2) Can the conditional replacement be applied to multiple replacement (i.e., replacing A1 and A2 at the same time with "Bad" but only under similar conditions?