python - 根据分隔符吐出一列
问题描述
我想从我的数据框中的列中提取一些信息:
例子
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 ...
重要的是要考虑第一个破折号,因为我可能会在文本中包含更多破折号。它似乎是这个符号-
,但也许它可以是一个更长的破折号。我从我的数据集中复制并粘贴,但在这里复制它似乎略有不同。
解决方案
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 ...
推荐阅读
- azure - 在 Azure Functions 中,在代码中运行 Cosmos DB 查询
- python - AttributeError: 'dict' 对象没有属性 'append' 试图写入 .JSON 文件
- matlab - 如何使用 MATLAB 在嵌套的 for 循环中使每个数组相互相乘?
- c# - 需要将两个 observable 压缩在一起
- javascript - 如何在单击提交按钮之前从数据库中获取值并显示计算值
- javascript - JS:在命名函数中调用函数
- javascript - 如何通过标签名称找到伟大的父节点onclick javascript中的嵌套子节点?
- r - 使用kmeans()后:如何判断哪个点属于哪个组?
- regex - 在 Haskell 中实现 Regex 时遇到问题
- ruby - Ruby 多进程同步