[英]Python string split on multiple characters
如果您提供有关格式的更多详细信息,我可以更新正则表达式。
import pandas as pd
df = pd.DataFrame({'columnA': ['apple:50-100(+)', 'peach:75-125(-)', 'banana:100-150(+)']})
pattern = r"(.*):(\d+)-(\d+)\(([+-])\)"
new_df = df['columnA'].str.extract(pattern)
df
:
columnA
0 apple:50-100(+)
1 peach:75-125(-)
2 banana:100-150(+)
new_df
:
0 1 2 3
0 apple 50 100 +
1 peach 75 125 -
2 banana 100 150 +
re.split
可用于拆分与模式匹配的任何字符串。 对于您给出的示例,以下内容应该有效
re.split(r'[\:\-\(\)]+', your_string)
它在所有冒号、连字符和括号(“:”、“-”、“(”和“)”)上拆分字符串
这会导致一个空字符串作为列表的最后一个成员,您可以将其切掉
re.split(r'[\:\-\(\)]+', your_string)[:-1]
或者过滤掉空值
filter(None, re.split(r'[\:\-\(\)]+', your_string))
这是一个替代方案:
Python 3.7.5 (default, Oct 17 2019, 12:16:48)
[GCC 9.2.1 20190827 (Red Hat 9.2.1-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> import pandas as pd
>>> split_it = re.compile(r'(\w+):(\d+)[-](\d+)\((.)\)')
>>> df = pd.DataFrame(split_it.findall('apple:50-100(+)'))
>>> df
0 1 2 3
0 apple 50 100 +
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.