I have the following dataframe.
ID LOC Alice Bob Karen
0 1 CH 9|5 6|3 4|4
1 2 ES 1|1 0|8 2|0
2 3 DE 2|4 6|6 3|1
3 4 ES 3|9 1|2 4|2
Alice and Bob columns contain string values. I want to reverse the strings in these columns conditional on the value of another column. For example, where LOC==ES, reversing the strings in the corresponding columns would look like:
ID LOC Alice Bob Karen
0 1 CH 9|5 6|3 4|4
1 2 ES 1|1 8|0 0|2
2 3 DE 2|4 6|6 3|1
3 4 ES 9|3 2|1 2|4
Is there a fast way to perform this operation on all matching rows in a csv file with thousands rows?
Thank you.
#cols = ['Alice','Bob']
In [17]: cols = df.columns.drop(['ID','LOC'])
In [18]: df.loc[df.LOC=='ES', cols] = df.loc[df.LOC=='ES', cols].apply(lambda x: x.str[::-1])
In [19]: df
Out[19]:
ID LOC Alice Bob Karen
0 1 CH 9|5 6|3 4|4
1 2 ES 1|1 8|0 0|2
2 3 DE 2|4 6|6 3|1
3 4 ES 9|3 2|1 2|4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With