Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中捕获字符串中的第一个数字元素?_Python_Regex_Pandas_String - Fatal编程技术网

如何在python中捕获字符串中的第一个数字元素?

如何在python中捕获字符串中的第一个数字元素?,python,regex,pandas,string,Python,Regex,Pandas,String,我有下面的代码 import re age = [] txt = ('9', "10y", "4y",'unknown') for t in txt: if t.isdigit() is True: age.append(re.search(r'\d+',t).group(0)) else: age.append('unknown') print(age) 我得到: ['9','unknown','unk

我有下面的代码

import re
age = []

txt = ('9', "10y", "4y",'unknown')
for t in txt:
    if t.isdigit() is True:
        age.append(re.search(r'\d+',t).group(0))
    else:
        age.append('unknown')
print(age)
我得到: ['9','unknown','unknown','unknown']

所以我得到了9,但我还需要得到第二个位置的10,第三个位置的4,最后一个位置未知。
谁能给我指出正确的方向吗?
谢谢你的帮助

我们可以利用
re.search
在未找到任何数字时返回
None
这一事实:

txt = ('9', "10y", "4y",'unknown')
age = []
for t in txt:
    num = re.search('\d+', t)
    if num:
        age.append(num.group(0))
    else:
        age.append('unknown')

由于您标记了熊猫,如果您有一列,请使用str.extract:

pd.Series(txt).str.extract('(\d+)')

看看这个。因此len函数检查字符串是否大于1,然后如果字符串的最后一个字母不是数字,则字符串的最后一个字母将替换为一个空格。然后,它将遵循算法的其余部分。您可以对其进行更多修改以满足您的需求,因为您没有指定太多。

谢谢!!!就这样!哎呀……我应该在这个问题上加上更多的上下文……我一直在为一家宠物收容所做一些志愿工作……数据框中的一列是xY yM,已经好几年好几个月了。我只需要年龄来做一些分析,所以熊猫的想法可能是最好的选择。再次感谢!谢谢,这真的很酷!我不知道为什么它被选为复制我没有看到任何复制。我认为这个标志是正确的。在提交问题之前,我确实经历了一个小时的堆积如山的过程。我没有看到与我的问题类似的答案。这个问题的答案类似于@Erfan pandas解决方案。我一定错过了。谢谢大家的帮助
pd.Series(txt).str.extract('(\d+)')
0      9
1     10
2      4
3    NaN
dtype: object

import re
age = []

txt = ('9', "10y22", "4y", 'unknown')

for t in txt:
    res = re.findall('[0-9]+', t)
    if res:
        age.append(res[0])
    else:
        age.append("unknown")
import re


age = []

txt = ('9', "10y", "4y",'unknown')
for t in txt:
    if len(t) > 1 and not t.isdigit():
        t = t.replace(t[-1], '')
    if t.isdigit() is True:
        age.append(re.search(r'\d+',t).group(0))
    else:
        age.append('unknown')
print(age)