Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 915
nofutur Avatar asked Jul 26 '17 18:07

nofutur


1 Answers

#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
like image 152
MaxU - stop WAR against UA Avatar answered Sep 19 '22 22:09

MaxU - stop WAR against UA