gpt4 book ai didi

python - 提取系列对象之间的字符串

转载 作者:太空宇宙 更新时间:2023-11-03 21:29:49 25 4
gpt4 key购买 nike

我有一个 A 列,其观察结果类似于前 ABC01P20180821123758。观察结果可能存在变化,例如 ABC01N20180821123758(“N”,而不是“P”)。或者观察可以是 P20180706035955-1 或 45312343P20180821143257-1

我只想提取 P 或 N 之后的年、月和日期。

在这里尝试了不同的帖子和解决方案。我尝试的解决方案之一如下:尽管我能够提取 P 和 N 之后的值,但它会在之后给我整个字符串。我无法从这里提取年、月和日期,因为这是一个系列,我无法将“match”作为字符串传递,我陷入了困境。请帮忙。有没有更好的方法来做到这一点。

对于列名中的行:

match = re.search('P(\d+)', line)
match = re.search('N(\d+)', line)

if match:
print (match.group(1))

输出 print (match.group(1)) 给出 P 或 N 之后的整个字符串。现在,当我打印(匹配)时,它给出的输出为“无”。

如何将这些值放入字符串和子集或将其拆分?

_______________更新代码__________________________________

对于 df.column1 中的行: match = re.search('P|N([0-9]{6})', line)

if match:
print(match.group(1))
for line in {match.group(1)}: #for every observation in the column that is matched
line = 1
while line < len(match.group(1)):

a = pd.DataFrame({'Date': {match.group(1)}}) #created a new column in a new DF. This is where my problem is. Eventhough iPython console is printing all observations that matched, when I write to excel, only the last observation is written that too in {} format. I am unable to fix this.

a.append('Date', axis=1)
line += 1

frames = [df, a]

result = pd.concat(frames) #concatenated dfs
print(result)

result.to_csv("D://A.csv", index = False)

最佳答案

尝试模式r"(P|N)(\d{8})"

例如:

import re

s = """ABC01P20180821123758 ABC01N20180821123758 P20180706035955-1 45312343P20180821143257-1"""
print(re.findall(r"(P|N)(\d{8})", s))

输出:

[('P', '20180821'), ('N', '20180821'), ('P', '20180706'), ('P', '20180821')]

关于python - 提取系列对象之间的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53594610/

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