gpt4 book ai didi

python - 根据定界符吐出一列

转载 作者:行者123 更新时间:2023-12-02 16:14:49 25 4
gpt4 key购买 nike

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

例子

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 ...

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

最佳答案

尝试将 str.extract 与正则表达式结合使用。

例如:

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 ...

关于python - 根据定界符吐出一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67037790/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com