nofutur nofutur - 1 year ago 87
Python Question

Reverse string columns in a pandas subset dataframe

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.

Answer Source

Use df.loc to get your row slices, then apply string reverse [::-1] operation on the Alice and Bob columns with df.applymap.

In [533]: df.loc[df['LOC'] == 'ES', ['Alice', 'Bob']] = \
                 df.loc[df['LOC'] == 'ES', ['Alice', 'Bob']].applymap(lambda x: x[::-1])

In [534]: df
Out[534]: 
   ID LOC Alice  Bob Karen
0   1  CH   9|5  6|3   4|4
1   2  ES   1|1  8|0   2|0
2   3  DE   2|4  6|6   3|1
3   4  ES   9|3  2|1   4|2
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download