0
Q
在大熊猫
A
回答
0
使用Series.str.replace
执行正则表达式字符串替换:
df['Name'] = df['Name'].str.replace(r'(.+),\s+(.+)', r'\2 \1')
的正则表达式模式(.+), (.+)
装置
( begin group #1
.+ match 1-or-more of any character
) end group #1
, match a literal comma
\s+ match 1-or-more whitespace characters
( begin group #2
.+ match 1-or-more of any character
) end group #2
第二个参数r'\2 \1'
,讲述str.replace
替换匹配组#2,接着该模式的子由一个空间,然后是组#1。
import pandas as pd
names = '''\
John Snow
Black, Jack
Jim Bean/
Draper, Don
'''
df = pd.DataFrame({'Name': names.splitlines()})
# Name
# 0 John Snow
# 1 Black, Jack
# 2 Jim Bean/
# 3 Draper, Don
df['Name'] = df['Name'].str.replace(r'(.+),\s+(.+)', r'\2 \1')
产生
Name
0 John Snow
1 Jack Black
2 Jim Bean/
3 Don Draper
0
也许你可以尝试这样的事情与reverse
功能:
d = {'name':['Bran Stark','Jon Snow','Rhaegar Targaryen']}
df = pd.DataFrame(data=d)
df['new name'] = df['name'].apply(lambda x : ', '.join(reversed(x.split(' '))))
print(df['new name'])
0 Stark, Bran
1 Snow, Jon
2 Targaryen, Rhaegar
相关问题
- 1. 在大熊猫
- 2. 在大熊猫
- 3. 在大熊猫
- 4. 在大熊猫
- 5. 在大熊猫
- 6. 在大熊猫
- 7. 在大熊猫
- 8. 在大熊猫
- 9. 在大熊猫
- 10. 在大熊猫
- 11. 在大熊猫
- 12. 在大熊猫
- 13. 大熊猫与熊猫
- 14. 熊猫 - str.contains()在大熊猫查询
- 15. 大熊猫在Python
- 16. set_index在大熊猫
- 17. 大熊猫:在DF
- 18. 大熊猫 - 在大块
- 19. 熊猫大CSV
- 20. 与大熊猫
- 21. 大熊猫
- 22. 与大熊猫
- 23. 大熊猫
- 24. 大熊猫由
- 25. 对大熊猫
- 26. 与大熊猫
- 27. 与大熊猫
- 28. 熊猫群大熊猫字典
- 29. 大熊猫:错误时回路在给定的大熊猫行
- 30. 遍历在大熊猫值
我相信OP问任何其他清洁提示。你可以很容易地(正如我确信你知道的那样)在你的正则表达式的末尾添加一个'/?'来捕获任何尾随的''''。 – piRSquared
谢谢unutbu,Stefan和谢安琪的回答!我接受这个,因为它是最灵活的,也是正则表达式的解释。 @Stefan你的回答非常优雅,我可能会在我的解决方案中使用它的概念。谢谢! – unpairestgood