Python 基于分隔符吐出列
我想从我的数据框中的列中提取一些信息: 范例Python 基于分隔符吐出列,python,regex,pandas,Python,Regex,Pandas,我想从我的数据框中的列中提取一些信息: 范例 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
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
及
重要的是要考虑第一个破折号所在的地方,因为我可能在文本中包含更多的破折号。
它似乎是这个符号-
,但它可能是一个较长的破折号。我从数据集中复制并粘贴了它,但在这里复制它似乎略有不同。Series.str.split
我们可以围绕分隔符\s-\s
拆分列Col
,并将拆分次数限制为1
,以避免多次出现\s-\s
df[['Col1', 'Col2']] = df['Col'].str.split(r'\s—\s', n=1, expand=True)
尝试将
str.extract
与正则表达式一起使用
Ex:
import pandas as pd
df[['Col1', 'Col2']] = df['Col'].str.extract(r"(\d+ points?)?\s*\—?\s*(.*)", expand=True)
print(df)
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 some other text ... NaN some other text ...
3 1 point — "what to say more?" 1 point "what to say more?"
4 13 points — ... 13 points ...
5 11 points — 1234 ... 11 points 1234 ...
输出:
import pandas as pd
df[['Col1', 'Col2']] = df['Col'].str.extract(r"(\d+ points?)?\s*\—?\s*(.*)", expand=True)
print(df)
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 some other text ... NaN some other text ...
3 1 point — "what to say more?" 1 point "what to say more?"
4 13 points — ... 13 points ...
5 11 points — 1234 ... 11 points 1234 ...
你试过
str.extract()吗
谢谢你的回答,Shubham Sharma。我注意到,如果没有-,原始数据集中会丢失一些文本。我没有得到任何文本,而不是文本。在上面的例子中,如果是其他文本…
。你能检查一下你是否也会遇到这种情况吗?@Val我们没有丢失任何文本实际上,如果没有-
,那么所有then文本都将出现在第一列。但是如果您希望文本出现在2列
中,那么我们可能必须使用提取
,如@Rakesh在其答案中所示。感谢Rakesh。如果有多个术语(例如,分/分或分隔符前的分数/分数),因为我可以更改它?例如,我可能在同一列中有1分-…
,但也有10分-bla-bla-bla
。(\d+分?\d+分?)\s*-?\s*(*)
?