[英]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. Alice和Bob列包含字符串值。 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:
例如,在LOC == ES的情况下,反转相应列中的字符串将如下所示:
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? 有没有快速的方法在csv文件中有数千行的所有匹配行上执行此操作?
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
. 使用
df.loc
让你排片,然后应用串反向[::-1]
上的操作Alice
和Bob
的列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'
: 您可以尝试使用
.apply()
,如下例所示,其中列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 在我的回答中注意,
[::-1]
是一种反转字符串的方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.