pandas 在"loc"之后如何“替换"工作? [英] Pandas how can 'replace' work after 'loc'?
本文介绍了 pandas 在"loc"之后如何“替换"工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经尝试了很多次,但是在使用"loc"后,"replace"似乎无法正常工作. 例如,我想用正则表达式将'conlumn_a'值为'apple'的行替换为'conlumn_b'.
I have tried many times, but seems the 'replace' can NOT work well after use 'loc'. For example I want to replace the 'conlumn_b' with an regex for the row that the 'conlumn_a' value is 'apple'.
这是我的示例代码:
df.loc[df['conlumn_a'] == 'apple', 'conlumn_b'].replace(r'^11*', 'XXX',inplace=True, regex=True)
示例:
conlumn_a conlumn_b
apple 123
banana 11
apple 11
orange 33
我期望的'df'结果是:
The result that I expected for the 'df' is:
conlumn_a conlumn_b
apple 123
banana 11
apple XXX
orange 33
有人遇到过需要在"loc"之后用正则表达式替换"的问题吗?
Anyone has meet this issue that needs 'replace' with regex after 'loc' ?
或者你们还有其他一些好的解决方案?
OR you guys has some other good solutions ?
非常感谢您的帮助!
推荐答案
我认为您双方都需要过滤器:
I think you need filter in both sides:
m = df['conlumn_a'] == 'apple'
df.loc[m,'conlumn_b'] = df.loc[m,'conlumn_b'].astype(str).replace(r'^(11+)','XXX',regex=True)
print (df)
conlumn_a conlumn_b
0 apple 123
1 banana 11
2 apple XXX
3 orange 33
这篇关于 pandas 在"loc"之后如何“替换"工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文