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
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
You could try using .apply()
as follows for your example condition where column LOC == 'ES'
:
df['Alice'] = df[['LOC','Alice']].apply(lambda x: x['Alice'][::-1] if x['LOC'] == 'ES' else x['Alice'], axis=1)
Note in my answer that [::-1]
is a way to reverse a string
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.