首页 > 解决方案 > 根据分隔符吐出一列

问题描述

我想从我的数据框中的列中提取一些信息:

例子

Col
7 points  — it is an example ...
13 points  — as above ...
some other text ...
1 point  — "what to say more?"
13 points  — ...
11 points  — 1234 ...

我正在使用 str.contain 提取第一部分(即,第一个破折号之前的所有信息,其中有。

m = (df['Col'].str.contains(r'(?i)^\d+\spoint | points'))
df[m]

我仍然得到相同的原始列(所以没有提取)。我的输出将包含两列,一列没有点信息 (Col1),另一列 (Col2) 包含提取的文本。

Col1
7 points  
13 points 
# need to still keep the row, even if empty
1 point 
13 points
11 points

Col2       
it is an example ...
as above ...
some other text ...
"what to say more?"
...                                                   
1234 ...

重要的是要考虑第一个破折号,因为我可能会在文本中包含更多破折号。它似乎是这个符号-,但也许它可以是一个更长的破折号。我从我的数据集中复制并粘贴,但在这里复制它似乎略有不同。

标签: pythonregexpandas

解决方案


Series.str.split

Col我们可以在分隔符周围拆分列\s—\s并将拆分次数限制为1,以避免在多次出现时拆分\s—\s

df[['Col1', 'Col2']] = df['Col'].str.split(r'\s—\s', n=1, expand=True)

                                Col        Col1                  Col2
0  7 points  — it is an example ...   7 points   it is an example ...
1         13 points  — as above ...  13 points           as above ...
2    1 point  — "what to say more?"    1 point    "what to say more?"
3                  13 points  — ...  13 points                    ...
4             11 points  — 1234 ...  11 points               1234 ...

推荐阅读